A. Moore - 4 months ago 29

Java Question

My program’s purpose is to receive a binary number (1’s and 0’s) as input, verify that it is a binary number, deny the input if it is not a binary number and continue prompting the user until they enter a binary number, and then output how many ones and zeros are in that binary number.

Here’s the problem I am running into: While my program does output how many ones and zeros are in the number, even when I do enter a proper binary number, my output still says “ERROR: Not a binary number.” For example, if my input was 10001, the output would be this-

Please enter a binary number.

10001

There are 2 ones in the binary number.

There are 3 zeros in the binary number.

ERROR: Not a binary number.

Please enter a binary number.

What did I do wrong in my code?

`import java.util.Scanner;`

public class NewClass

{

public static void main( String [] args )

{

Scanner scan = new Scanner( System.in);

int i = 0, count1 = 0, count0 = 0;

String number;

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

number = scan.next();

String number1 = "1";

while ((i = number.indexOf(number1, i++)) != -1) {

count1++;

i += number1.length();

}

System.out.println("There are "+ count1 + " ones in the binary number.");

String number2 = "0";

while ((i = number.indexOf(number2, i++)) != -1) {

count0++;

i += number2.length();

}

System.out.println("There are "+ count0 + " zeros in the binary number.");

int total = (count1 + count0);

int length = number.length();

if (length != total);

{

System.out.println("ERROR: Not a binary number.");

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

number = scan.next();

}

}

}

Answer

Try this code. First, you can use scan.nextLine() method to get user's input. and Second, you don't need use two while loops separately for zeros and ones. finally, if there is wrong input such as 2, 3 or else. It should be loop infinitely.

```
import java.util.Scanner;
public class NewClass {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
int i = 0, count1 = 0, count0 = 0;
String number;
char number1 = '0';
char number2 = '1';
int total;
while(true){
System.out.println("Please enter a binary number.");
number = scan.nextLine();
char [] charArray = number.toCharArray();
while(i < charArray.length){
if(charArray[i] == number1){
count0++;
} else if(charArray[i] == number2) {
count1++;
}
i++;
}
total = count0 + count1;
if(charArray.length == total){
System.out.println("There are " + count0 + " zeros in the binary number.");
System.out.println("There are " + count1 + " ones in the binary number.");
break;
} else {
System.out.println("ERROR: Not a binary number.");
}
}
}
}
```