简体   繁体   中英

While loop that checks for an 8 digit binary number

I'm struggling to succesfully write this without errors. It for example i will type 101 and 103, but on the 3rd number if i type an 8 digit binary like 10101010 is still displays that it isnt binary. The while loop should check if the number is 1) binary and 2) 8 digits.

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
            }
        }
    }
}

I wouldn't use a loop to check every character. I would use String.matches() to test if the input is only 1's and 0's:

while (!number.matches("[01]{8}")) {
    // read number again
}

As an afterthought, if you wanted a similar solution that does not use regex:

while (number.length() != 8 || !number.replace("0", "").replace("1", "").isEmpty()) {
    // read number again
}

Your Boolean condition is wrong, you need to check with && instead of ||

What you want to check is that the value of the character is different from 48 and 49. If you check with or then the result is always true because the character value cannot be both 48 and 49 at the same time.

i dont really get your question.

binaryfail = true;
     while (binaryfail == true){
          System.out.println("The number you entered is not a binary number or 8 digits");
     }

This has to result in an infinite loop, that shows that you havent entered a binary number

Although there are better ways to do this, the following fixes your code with minimal changes:

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");

Note - I updated this from my original post; this now works...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM