我正在努力成功地写下这个没有错误。例如,我将输入101和103,但是在第3个数字上,如果我输入一个8位二进制数字,如10101010仍然显示它不是二进制。 while循环应检查数字是否为1)二进制和2)8位数。
while (number.length() != 8)
{
for(int i = 0; i < number.length(); i++)//for loop with accumulator
{
if (number.charAt(i) != 48 || number.charAt(i) != 49)
{
binaryfail = true;
while (binaryfail == true)
{
System.out.println("The number you entered is not a binary number or 8 digits");
number = Keyboard.nextLine();//re-entry
}
}
}
}
答案 0 :(得分:3)
我不会使用循环来检查每个角色。我会使用String.matches()
来测试输入是否仅为1和0:
while (!number.matches("[01]{8}")) {
// read number again
}
作为事后的想法,如果你想要一个类似的解决方案不使用正则表达式:
while (number.length() != 8 || !number.replace("0", "").replace("1", "").isEmpty()) {
// read number again
}
答案 1 :(得分:2)
您的布尔条件错误,您需要使用&&
代替||
您要检查的是该字符的值与48 和 49不同。如果您使用或进行检查,则结果始终为{{1}因为字符值不能同时为48和49。
答案 2 :(得分:1)
我真的不明白你的问题。
binaryfail = true;
while (binaryfail == true){
System.out.println("The number you entered is not a binary number or 8 digits");
}
这必须导致无限循环,表明您没有输入二进制数
答案 3 :(得分:-1)
虽然有更好的方法可以做到这一点,但以下代码修改了您的代码:
String number;
Boolean binaryfail;
number Keyboard.nextline();
while (true)
{
binaryfail = (number.length() != 8); // set "fail" flag to true if length is wrong
for(int i = 0; i < number.length() && !binaryfail; i++) // loop - exit if fail
{
if (number.charAt(i) != 48 && number.charAt(i) != 49) // <<< note && not ||
{
binaryfail = true; // this causes the for loop to stop
}
}
if (binaryfail == true)
{
System.out.println("The number you entered is not a binary number or 8 digits");
number=Keyboard.nextline(); // so try again...
}
else break; // got here: so no failure - must have found a good number
}
System.out.println("Congratulations - " + number + " is an eight digit binary number");
注意 - 我从原来的帖子中更新了这个内容;这现在有效...