简体   繁体   中英

Java: Please tell Me what's wrong?

Here's the code:

System.out.println("Qualifies for instate rate: ");
instate = keyboard.nextLine();
while((instate.equalsIgnoreCase("yes") == false || instate.equalsIgnoreCase("no") == false))
{
    System.out.println("Enter either yes or no:");
    instate = keyboard.nextLine();
}

My problem is the output is never-ending; here's the output

Enter either yes or no:
no
Enter either yes or no:
no
Enter either yes or no:
yes
Enter either yes or no:
yup
Enter either yes or no:

It doesn't even matter what I enter in the keyboard. Please tell me the problem and possible solutions.

Change:

System.out.println("Qualifies for instate rate: ");
instate = keyboard.nextLine();
while((instate.equalsIgnoreCase("yes") == false || instate.equalsIgnoreCase("no") == false))
{
    System.out.println("Enter either yes or no:");
    instate = keyboard.nextLine();
}

To:

System.out.println("Qualifies for instate rate: ");
instate = keyboard.nextLine();
while((instate.equalsIgnoreCase("yes") == false && instate.equalsIgnoreCase("no") == false))
{
    System.out.println("Enter either yes or no:");
    instate = keyboard.nextLine();
}

Change your condition inside the while loop to be :

(instate.equalsIgnoreCase("yes") == false && instate.equalsIgnoreCase("no") == false)

It because of DeMorgan's Rule in Boolean Algebra:

!A || !B = !(A && B)
!A && !B = !(A || B)

将您的条件更改为以下内容:

!Arrays.asList(new String[]{"yes", "no"}).contains(instate.toLowerCase())

In your while loop condition:

while((instate.equalsIgnoreCase("yes") == false || instate.equalsIgnoreCase("no") == false))
{
    System.out.println("Enter either yes or no:");
    instate = keyboard.nextLine();
}

You have it testing if either "yes" is not the input or "no" is not the input, so if they type "yes", it will see that they didn't type "no", then repeat the loop, and if they typed "no", it will see that yes was not typed and repeat again. Change the || operator to the && operator so it makes sure that if either "yes" or "no" is typed, and if neither is typed, then it will repeat.

while((instate.equalsIgnoreCase("yes") == false && instate.equalsIgnoreCase("no") == false))
{
    System.out.println("Enter either yes or no:");
    instate = keyboard.nextLine();
}

这行instate.equalsIgnoreCase("yes")已经返回一个boolean因此您无需再次进行比较。

while((!instate.equalsIgnoreCase("yes")) && (!instate.equalsIgnoreCase("no")))

One of the boolean expression in the while condition will always be true. "instate" cannot be "yes" and "no" at the same time. If you like to terminate the loop on "no" input, try

while (!instate.equalsIgnoreCase("no")) {
} 

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