我正在努力成功地写出这个而不出现错误。例如,我将输入 101 和 103,但在第三个数字上,如果我输入 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
}
}
}
}
最佳答案
我不会使用循环来检查每个字符。我会使用 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
}
关于java - 检查 8 位二进制数的 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22623917/