title: Checking if String entered is a binary numer, getting incorrect output
body: <p>I am trying to write a program that will check if the user-entered string is a binary number, and if it is, it will output the number of 1s in the number.  I had this working fine with an integer value, but since an int can't hold more than 2 billion or whatever the max value is, I am trying to rewrite it to work with Strings.</p>
  
  <p>As of right now, any number I enter will output "Number entered is not binary." and when I enter 0, I will get a StringIndexOutofBoundsException. I am a fairly novice programmer, so forgive any obvious errors I may have missed, I am just asking for a possible solution to my problem or a push in the right direction.  Here is my code (after trying to make it work with Strings rather than integers):</p>
  
  <pre><code>    import java.util.*;
  
      public class BinaryHW {
      public static void main(String[] args) {
  
    Scanner kb = new Scanner(System.in);
    System.out.println("Enter a binary number: ");
    String bin = kb.nextLine();
  
    //the method I used to check whether or not user entered a binary
    //number requires changing the value of 'bin'.
    //Therefore, 'origBin' set equal to 'bin' for later use.
  
    String origBin = bin;
    int count = 0;
  
    boolean isBinary = true;
    /* if bin = 0, then this loop will be skipped because 
     * 0 is a binary number and need not be checked.
     */
  
    while (Integer.parseInt(bin) != 0) {
  
       int lastDigit = bin.charAt(bin.length() - 1);
  
       if (lastDigit &gt; 1) {
          System.out.println("Number entered is not binary.");
          isBinary = false;
          break;
  
       } else {
          bin = bin.substring(bin.length() - 2);
       }
    }  
    //Again, the method I used to count the 1s in the bin number
    //requires changing the value of origBin, so origBin2 is introduced 
  
    String origBin2 = origBin;
  
    for (int i = 0; i &lt; origBin.length(); i++) {
  
       if (origBin.charAt(origBin.length() - 1) == 1) {
          count ++;
          origBin2 = origBin.substring(origBin2.length() - 2);
  
       } else {
          origBin2 = origBin.substring(origBin2.length() - 2);
  
       }
  
    }  
  
    if (isBinary)
       if (count == 1)
       System.out.println("There is " 
          + count + " 1 in the binary number entered.");
       else 
       System.out.println("There are " 
          + count + " 1s in the binary number entered.");
  
       }
   }
  </code></pre>