计算二进制数字字符串中的“1”-Java
这是我代码的一部分,我被指示编写一个程序,接受二进制数作为字符串,并且只有当1的总数为2时才会显示Accepted。事情还有很多,但我现在的问题是要数到1。如果有人能为我指出错误的方向,我将不胜感激计算二进制数字字符串中的“1”-Java,java,string,binary,numbers,counting,Java,String,Binary,Numbers,Counting,这是我代码的一部分,我被指示编写一个程序,接受二进制数作为字符串,并且只有当1的总数为2时才会显示Accepted。事情还有很多,但我现在的问题是要数到1。如果有人能为我指出错误的方向,我将不胜感激 import java.util.Scanner; public class BinaryNumber { public static void main( String [] args ) { Scanner scan = new Scanner(System.in);
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( );
}
问题是如果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);
c=='1'&&c=='0'永远不会是真的。您确实需要重新格式化此代码。到目前为止,我已经花了3分钟试图找出if语句的开始和结束位置。我的教授是那个让我设置该条件的人…好了…有什么建议吗?另外,我试着在疯狂状态之前进行计数,不走运:如果你把你的电脑放在一个装有放射性物质和盖革计数器的盒子里,可能两者都是真的……也许这是c='1'| c='0'的拼写错误