这是我代码的一部分,我被指示编写一个程序,该程序接受二进制数作为字符串,并且仅当 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/