How to clarify whether the user's input was a binary number? : <p>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. </p>

<p>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. </p>

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

<pre><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.");






 }
</code></pre>

<p>}</p>
