java - 计算二进制数字字符串中的 '1' - Java

标签 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( );
                   }

最佳答案

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

关于java - 计算二进制数字字符串中的 '1' - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20156426/

相关文章:

java - Maven 格式错误的 POM(无效 token )

java - 多线程 QuickSort 比普通 QuickSort 花费更长的时间

java - Tomcat 不重新加载 jsp 页面

python - 从大型二进制文件中读取数据的任何有效方法?

c++ - 二进制数据 : write an entire object into a file or separated variables (no object)? 哪个性能更好

java - Spring aop切入点表达式跨其他项目不适用

java - 安卓。替换字符串中的 * 字符

javascript - 如何在 javascript/jquery 中分割字符串并测试字符串的开头?

linux - 镜像字符串

c - 如何获取和存储二进制值进行运算?