0

I've written a java program that converts a string of bits to its equivalent non-negative integer but I do not know how to add an error message when a character other than "1" and "0" is displayed. I want the following message "Error -- The string should consist of 1s and 0s only." to print and the program to stop. Please help! Here is my code so far:

import java.util.Scanner;
class BinaryToDecimal {
   public static void main(String args[]) {
    Scanner input = new Scanner( System.in );
    System.out.print("Enter a binary number: ");
    String binaryString =input.nextLine();
    System.out.println ("The  original string you entered:" binaryString);
    System.out.println ("The equivalent integer is: "+Integer.parseInt(binaryString,2));
    }
}
csiu
  • 3,159
  • 2
  • 24
  • 26
Greens28
  • 1
  • 2

2 Answers2

1

One common way to do the validations is using Regular expressions, in this case the pattern that you are looking for is 0 or 1.

System already has methods that display errors and/or exits the execution of the program

Carlos Monroy Nieblas
  • 2,225
  • 2
  • 16
  • 27
0

You can check if a character is not either a 1 or 0 after each nextLine() call. i.e.:

String binaryString = input.nextLine();
for(char c : binaryString.toCharArray())
{
    if(!((c == '1') && (c == '0'))) System.err.println(ERROR_MESSAGE);
}

Then print to the standard error stream System.err (which is just what an error message does) if an incorrect character is entered. Note that you're probably also going to want to include some code that stops the program from trying to convert the binary if an incorrect character has been entered.

user2465510
  • 99
  • 10