A. Moore A. Moore - 27 days ago 12
Java Question

How to clarify whether the user's input was a binary number?

I was required to make a code that accepted a binary number (1's and 0's) and then counted how many ones were in that binary number. My code fulfills this purpose.

The second part of the exercise is this: if the user enters a number that is NOT binary, I must output that there is an error and keep prompting the user until they give a binary number.

Can someone show me how to incorporate this? I have tried several times but cannot make it click. Thanks! Here is my code.

import java.util.Scanner;

public class NewClass
{
public static void main( String [] args )
{
Scanner scan = new Scanner( System.in);

int i = 0, count = 0;
String number;

System.out.println("Please enter a binary number.");
number = scan.next();

String number1 = "1";


while ((i = number.indexOf(number1, i++)) != -1) {
count++;
i += number1.length();
}
System.out.println("There are "+ count + " ones in the binary number.");






}


}

Answer

You already know how to find all of the 1's; you should be able to do something similar to find all of the 0's.

If the sum of those two counts is not the length of the string, there must be at least one illegal character in it.

Comments