无效结果,将二进制数字中的1的数量相加

huangapple go评论81阅读模式
英文:

Invalid result adding the number of 1s in a binary number

问题

我正在将二进制数字中的1的个数相加,并得到了正确的结果。然而,当我用空格分隔数字时,它告诉我这个数字是奇数。

例如,输入:101 会返回偶数。然而,输入 1 0 1,会返回奇数。
我宁愿在输入包含空格时返回 "不是有效的输入",但我也不知道如何做到这一点。

出于某种原因,当我输入带有空格的名字,例如 "D a n",程序会自动将 "D" 分配为二进制数,然后跳过剩下的部分。

 //获取用户输入的名字
 System.out.println("输入你的名字 > ");
 String firstName = scan.next();
 
 System.out.print("输入一个二进制数字 > ");
 String num = scan.next();
  
 //从字符串名字中移除特殊字符/空格
 firstName = firstName.replaceAll("[^a-zA-Z0-9]", "");
 firstName = firstName.replaceAll("\\s", "");
 
 //提取首字母并大写
 String firstNameStart = firstName.substring(0, 1);
 firstNameStart = firstNameStart.toUpperCase();
 
 //提取剩余部分的名字
 String firstNameRemainder = firstName.substring(1);
 firstNameRemainder = firstNameRemainder.toLowerCase();     
 
 //拼接名字
 firstName = firstNameStart + firstNameRemainder;

 //正确打印名字
 System.out.println("\n" + firstName);

 //分析二进制数字
 if (String.valueOf(num).matches("[0-1]+")){
   
 // 二进制数字中1的总和
      int res = 0;
      for (int i = 0; i < num.length(); i++)
      {
        if(num.charAt(i) == '1')
          res = ++res;
      }     
         {
         if (res % 2 == 0)
             System.out.println("偶数。");
           else 
             System.out.println("奇数。");
           }
英文:

I am adding the number of ones in a binary number and have gotten the correct result. However, when I separate the number with spaces it tells me the number's odd.

For example input of: 101 will return even. However, an input of 1 0 1, will return odd.
I would rather return "Not a valid input" if the input contains spaces but I don't know how to do that either.

For some reason when I enter a name with spaces for example "D a n" the program automatically assigns "D" as the binary number and skips the rest.

 //Get user input of Name
 System.out.println( &quot;Enter your first name &gt; &quot; );
 String firstName = scan.next( );
 
 System.out.print( &quot;Enter a binary number &gt; &quot; );
 String num = scan.next( );
  
 //Remove special characters/spaces from String firstName
 firstName = firstName.replaceAll(&quot;[^a-zA-Z0-9]&quot;, &quot;&quot;);
 firstName = firstName.replaceAll(&quot;\\s&quot;, &quot;&quot;);
 
 //Extract first letter and capitalize
 String firstNameStart = firstName.substring(0, 1);
 firstNameStart = firstNameStart.toUpperCase( );
 
 //Extract remainder of name
 String firstNameRemainder = firstName.substring( 1 );
 firstNameRemainder = firstNameRemainder.toLowerCase( );     
 
 //Concatenate name
 firstName = firstNameStart + firstNameRemainder;

 //Print name properly
 System.out.println(&quot;\n&quot; + firstName);

 //Analyze binary number 
 if (String.valueOf(num).matches(&quot;[0-1]+&quot;)){
   
 // Sum of 1&#39;s in the binary number
      int res = 0;
      for (int i = 0; i &lt; num.length(); i++)
      {
        if(num.charAt(i) == &#39;1&#39;)
          res = ++res;
      }     
         {
         if (res % 2 == 0)
             System.out.println(&quot;Even.&quot;);
           else 
             System.out.println(&quot;Odd.&quot;);
           }

答案1

得分: 1

使用 Scanner#nextLine 来读取整行内容。

String firstName = scan.nextLine();
System.out.print("输入一个二进制数字 > ");
String num = scan.nextLine().replaceAll("[^01]", "");
英文:

Use Scanner#nextLine to read the entire line.

String firstName = scan.nextLine( );
System.out.print( &quot;Enter a binary number &gt; &quot; );
String num = scan.nextLine( ).replaceAll(&quot;[^01]&quot;, &quot;&quot;);

答案2

得分: 1

如果未明确设置,Scannernext()方法会在达到默认分隔符时停止,该分隔符是空格

  • 当您插入1 0 1时,它会在第一个空格处停止,并给出结果(1是奇数)。

  • 当您插入带有空格的名称时,第一部分将分配给名称,而第二个next()将继续读取第一个输入字符串,直到找到下一个空格为止(将其分配给您的代码中的二进制数)。

如果您希望分隔符为\n,也就是说,当您在键盘上按Enter时,您可以调用nextLine(),它将读取直到找到\n为止。

为了正确获取数字并检查它是偶数还是奇数,如果输入中有空格,您应该:

String line = scanner.nextLine().trim(); //移除空格
int number = Integer.parseInt(line);     //将其转换为数字

//检查整数是偶数还是奇数
if ((number & 1) == 0) 
{ 
   //它是偶数!
   ...
} 
else 
{ 
  //它是奇数!
  ....
}
英文:

If not specifically set, Scanner's next() method will stop when it reaches the default delimiter, which is a blank space.

  • When you insert 1 0 1 it stops at the first blank space, and gives you the result (1 is odd).

  • When you insert the name with blank spaces, the first part will be assigned to the name, and the second next() will just continue reading the first input string until the next blank space is found (assigning it to the binary number in your code).

If you want the delimiter to be \n, that is, when you push Enter on your keyboard, you could call nextLine(), which will instead read the line until \n is found.


In order to get the number correctly, and check wether it's even/odd, if there are blank spaces in the input, you should:

String line = scanner.nextLine().trim(); //removes whitespaces
int number = Integer.parseInt(line);     //converts it to a number

//check if the integer is even/odd
if ((number &amp; 1) == 0) 
{ 
   //it&#39;s even!
   ...
} 
else 
{ 
  //it&#39;s odd!
  ....
}

huangapple
  • 本文由 发表于 2020年7月24日 06:50:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63064226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定