File tree
Expand file treeCollapse file tree1 file changed
+73
-0
lines changed Expand file treeCollapse file tree1 file changed
+73
-0
lines changed Original file line number | Diff line number | Diff line change |
---|
|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class BinaryToDecimal { |
| 4 | + |
| 5 | +static int temp = 0; |
| 6 | + |
| 7 | +public static void main(String[] args) { |
| 8 | + |
| 9 | +int binaryInput; |
| 10 | + |
| 11 | +System.out.println("Program to convert Binary Code to Decimal.\n---"); |
| 12 | + |
| 13 | +Scanner sm = new Scanner(System.in); |
| 14 | + |
| 15 | +System.out.print("Enter the binary code (Make sure it contains only 0's and 1's): "); |
| 16 | + |
| 17 | +binaryInput = sm.nextInt(); |
| 18 | + |
| 19 | +if(checkBinary(binaryInput)) { |
| 20 | +end(); |
| 21 | +} |
| 22 | +else { |
| 23 | +binaryConvert(binaryInput); |
| 24 | +System.out.println(temp); |
| 25 | +sm.close(); |
| 26 | +end(); |
| 27 | +} |
| 28 | +} |
| 29 | + |
| 30 | +private static int binaryConvert(int num) { |
| 31 | + |
| 32 | +int n,x=0; |
| 33 | + |
| 34 | +while (num>0) { |
| 35 | +n = (int) java.lang.Math.pow(2, x); |
| 36 | +temp = temp + (num%10) * n; |
| 37 | +x=x+1; |
| 38 | +num=num/10; |
| 39 | +} |
| 40 | +return temp; |
| 41 | +} |
| 42 | + |
| 43 | +private static boolean checkBinary(int n) { |
| 44 | +int x; |
| 45 | +boolean flag = false; |
| 46 | +while(n>0) { |
| 47 | +x=n%10; |
| 48 | + |
| 49 | +if(flag ==true) { |
| 50 | +System.out.println("Validation Error: The Entered String is not a Binary Number."); |
| 51 | +break; |
| 52 | +} |
| 53 | +else { |
| 54 | +if(x==1 || x==0) { |
| 55 | + |
| 56 | +} |
| 57 | +else { |
| 58 | +flag = true; |
| 59 | +} |
| 60 | +} |
| 61 | +n=n/10; |
| 62 | +} |
| 63 | + |
| 64 | +return flag; |
| 65 | + |
| 66 | +} |
| 67 | + |
| 68 | +private static void end() { |
| 69 | +System.out.println("---\nThe Program has ended."); |
| 70 | +System.exit(0); |
| 71 | +} |
| 72 | + |
| 73 | +} |
You can’t perform that action at this time.
0 commit comments