java do while loop keeps looping after condition is met

前端 未结 3 2070
自闭症患者
自闭症患者 2021-01-27 00:32

I am a new java programmer and I am writing a program that sets 3 model numbers for 3 printers. If user inputs wrong values I want it to continue asking user for the model numbe

3条回答
  •  攒了一身酷
    2021-01-27 00:49

    There are several problems. This line is wrong:

    while(!s.equals(machine1) || (!s.equals(machine2)) || (!s.equals(machine3)) && (count < 2));
    

    s is a Scanner, not a String, this isn't a valid comparison. Substituting modelNumber for s gives:

    while(!modelNumber.equals(machine1) || (!modelNumber.equals(machine2)) || (!modelNumber.equals(machine3)) && (count < 2));
    

    This can't be false unless modelNumber, machine1, machine2, and machine3 are all the same value.

    Also testing count is messing this up and is redundant since you're testing it and breaking within the loop.

    It should be

    while(!modelNumber.equals(machine1) 
        && (!modelNumber.equals(machine2)) 
        && (!modelNumber.equals(machine3)));
    

    See DeMorgan's Laws. Applying this rule gives

    while(!(modelNumber.equals(machine1)
        || modelNumber.equals(machine2)
        || modelNumber.equals(machine3)))
    

    which may be easier to read.

    Also, if you substitute "return" for "break;" along with making the change to the do-while condition, it works. So there is something else going on. Calling break in the inner do-while causes control to return to the top of the outer while loop. Adding a boolean flag that is set before you break and which is tested in the outer while loop would be one way to solve this. Or just use return.

提交回复
热议问题