检查输入的String是否为二进制数,输出不正确

时间:2016-04-19 19:17:23

标签: java string binary

我正在尝试编写一个程序来检查用户输入的字符串是否是二进制数,如果是,则输出数字中的1的数量。我有一个整数值的工作正常,但由于int不能超过20亿或任何最大值,我试图重写它以使用字符串。

截至目前,我输入的任何数字都将输出“输入的数字不是二进制”。当我输入0时,我将得到一个StringIndexOutofBoundsException。我是一个相当新手的程序员,所以原谅我可能错过的任何明显的错误,我只是要求我的问题的可能解决方案或推动正确的方向。这是我的代码(在尝试使用Strings而不是整数之后):

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

     }
 }

1 个答案:

答案 0 :(得分:0)

我认为你过于复杂化了......简单地遍历你的二进制字符串,并跟踪到达的1的数量。如果找到0或1以外的数字,则报告该输入是非二进制数。以下是完成此操作的片段:

public static void main(String[] args) {

      Scanner kb = new Scanner(System.in);
      System.out.println("Enter a binary number: ");
      String bin = kb.nextLine();
      int oneCount = 0;
      boolean validBinaryNum = true;

      for (int i = 0; i < bin.length() && validBinaryNum; i++) {
          char currentChar = bin.charAt(i);
          if (currentChar == '1') oneCount++;
          else if (currentChar != '0') {
              validBinaryNum = false;
          }
      }

      if (validBinaryNum && bin.length() != 0) {
          System.out.println("Number of 1's: " + oneCount);
      } else {
          System.out.println("Number is not binary");
      }

}