Reputation: 33
I'm writing a java program to convert binary numbers into decimal numbers, I've managed to get my program to work in that regard.
My question is how do I make it so the user has to enter a binary number or else an error will pop up and the question will end? Also, How do I repeat my statement so the user can calculate multiple binary number conversions?
If you give an answer could you explain how each step works and show how the code should looks?
My current program is this:
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
int binarynum =input.nextInt();
int binary=binarynum;
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
System.out.println("Binary = "+binarynum+" Decimal = "+decimal); ;
}
Upvotes: 0
Views: 455
Reputation: 109567
You can use Scanner.hasNextInt(int radix)
and Scanner.nextInt(int radix)
with a radix of 2. Of course nextInt(2)
would do all your work, so:
System.out.println("Enter a binary number:");
while (!input.hasNextInt(2)) {
System.out.println("Only 0 and 1 allowed. Enter a binary number:");
input.nextLine(); // Skip the input line.
}
int binarynum = input.nextInt(); // input.nextInt(2) would give the result.
Scanner has for its next...()
methods corresponding test methods hasNext...()
.
Upvotes: 0
Reputation: 414
This version keeps on asking the user to give a binary value.
If it's not binary, an exception will be thrown.
Finally, to stop the process, you just have to enter END
as input.
public static void main(String[] args) {
while (true) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary number (END to exit): ");
try {
String inputValue = input.next();
if (inputValue.equals("END")) {
break;
}
if (!inputValue.matches("[01]+")) {
throw new Exception("Invalid binary input");
}
int binarynum = Integer.valueOf(inputValue);
int decimal = getDecimalValue(binarynum);
System.out.println("Binary = " + binarynum + " Decimal = " + decimal);
System.out.println();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
public static int getDecimalValue(int binary) {
int decimal = 0;
int power = 0;
while (true) {
if (binary == 0) {
break;
} else {
int temp = binary % 10;
decimal += temp * Math.pow(2, power);
binary = binary / 10;
power++;
}
}
return decimal;
}
Upvotes: 3