计算二进制数 Java 中的 '1



这是我代码的一部分,我被指示编写一个程序,该程序接受二进制数作为字符串,并且只有当1的总数为2时才会显示"Accepted"。它还有更多,但到了计算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( );
                   }

问题是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);

相关内容

  • 没有找到相关文章

最新更新