Java:请告诉我有什么问题?

时间:2015-03-21 00:26:38

标签: java

以下是代码:

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();
}

我的问题是输出永无止境;这是输出

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:

我在键盘输入的内容并不重要。 请告诉我问题和可能的解决方案。

6 个答案:

答案 0 :(得分:4)

变化:

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();
}

要:

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();
}

答案 1 :(得分:1)

将while循环内的条件更改为:

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

因为布尔代数中的DeMorgan规则:

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

答案 2 :(得分:0)

将您的情况更改为以下内容:

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

答案 3 :(得分:0)

在你的while循环条件中:

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

如果“是”不是输入或“否”不是输入,那么你测试它,所以如果输入“是”,它会看到它们没有输入“no”,然后重复循环,如果他们键入“否”,则会看到“是”未键入并再次重复。将||运算符更改为&&运算符,以确保输入“是”或“否”,如果两者都未键入,则会重复。

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

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

while条件中的一个布尔表达式将始终为true。 “instate”不能同时为“yes”和“no”。如果您想在“否”输入上终止循环,请尝试

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