So the program is supposed to convert a binary number to a decimal number, by first checking if it is a binary number and then converting. No matter what input I give, it always says that the input is not a binary number and I can't figure out why. Here is my code.
public class Conversion {
public static void main (String []args){
String binaryNumber = args[0];
if (checkBinary(binaryNumber)){
int decimalNumber = binaryToDecimal(binaryNumber);
System.out.print("The binary number " + binaryNumber + "is " + decimalNumber + "in base 10." );
}
else {
System.out.println("The input is not binary!");
}
}
public static boolean checkBinary(String binaryNumber){
for (int i=0; i < binaryNumber.length(); i++) {
char x = binaryNumber.charAt(i);
if (x != '0' && x != '1'){
return false;
}
}
return true;
}
public static int binaryToDecimal(String binaryNumber) {
int z = 1;
int y = 0;
for (int i = binaryNumber.length()- 1; i >= 0; i--){
if (binaryNumber.charAt(i)=='1'){
y += z;
}
z *= 2;
}
return y;
}
}
Integer.parseInt(String, int)where the second argument is a radix (say2).