用二进制数字串计算'1' - Java

时间:2013-11-22 23:32:18

标签: java string binary numbers counting

这是我的代码的一部分,我被指示编写一个接受二进制数字作为字符串的程序,如果1的总数为2,则只显示“已接受”。还有更多,但是到目前为止我的问题已经到了计算1的地步。如果有人能指出我的错误方向,那将是非常感激的。

import java.util.Scanner;


public class BinaryNumber
{
  public static void main( String [] args )
  {

   Scanner scan = new Scanner(System.in);
   String input;
   int count = 0;

   System.out.print( "Enter a binary number > ");
   input = scan.nextLine( );


    for ( int i = 0; i <= input.length()-1; i++)
    {
     char c = input.charAt(i);

      if ((c == '1') && (c == '0'))
           if (c == '1')
              {count++;}
              if (count == 2)
                 {System.out.println( "Accepted" );
                 }
                if (count != 2)
                   {System.out.println( "Rejected" );
                    System.out.print( "Enter a binary number > ");
                    input = scan.nextLine( );
                   }

1 个答案:

答案 0 :(得分:8)

问题是if ((c == '1') && (c == '0'))永远不会成真。

您需要检查该字符是否为1或0,然后检查它是否为“1”以增加您的计数器。

int count;
Scanner scan = new Scanner(System.in);
String input;
boolean notValid = false; //to say if the number is valid
do {
      count = 0;
      System.out.print("Enter a binary number > ");
      input = scan.nextLine();
      for (int i = 0; i <= input.length()-1; i++){
         char c = input.charAt(i);
         if(c == '0' || c == '1'){
             if (c == '1'){
                 count++;
                 if(count > 2){
                   notValid = true;
                   break; //<-- break the for loop, because the condition for the number of '1' is not satisfied
                 }
             }
         }
         else {
             notValid = true; // <-- the character is not 0 or 1 so it's not a binary number
             break;
         }
      }
 }while(notValid);  //<-- while the condition is not reached, re-ask for user input
 System.out.println("Done : " + input);