Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我的循环是否在Java中正确设置?_Java_While Loop - Fatal编程技术网

我的循环是否在Java中正确设置?

我的循环是否在Java中正确设置?,java,while-loop,Java,While Loop,我需要为不同的输出返回两条不同的错误消息。 一个表示用户输入为空,另一个表示用户输入是否为y或n。我遇到的问题是,我的代码只返回非y或n的错误消息,因为如果用户输入的不是y或n,我将返回该消息。该代码将返回正确的错误信息的空白错误一次,但之后是被困在只返回错误信息为Y或N。有没有关于如何解决这个问题的建议 while (choice.isEmpty()) { System.out.println("Error! This entery is required. Try again.")

我需要为不同的输出返回两条不同的错误消息。 一个表示用户输入为空,另一个表示用户输入是否为y或n。我遇到的问题是,我的代码只返回非y或n的错误消息,因为如果用户输入的不是y或n,我将返回该消息。该代码将返回正确的错误信息的空白错误一次,但之后是被困在只返回错误信息为Y或N。有没有关于如何解决这个问题的建议

while (choice.isEmpty()) 
{
    System.out.println("Error! This entery is required. Try again."); 
    choice = sc.nextLine(); 
} 

while (!(choice.equalsIgnoreCase ("y") || choice.equalsIgnoreCase ("n")))
{
    System.out.println ("Error! Please enter y, Y, n, or N. Try again ");
    choice = sc.nextLine(); 
}

您最好使用一个循环:

while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")) {
    if (choice.isEmpty()) {
        System.out.println("Error! This entry is required. Try again.");
    } else {
        System.out.println("Error! Please enter y, Y, n, or N. Try again.");
    }

    choice = sc.nextLine(); 
}

我认为这里只需要一个循环:

String choice = "";
do {
    choice = sc.nextLine();
    if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
        break;
    }
    else {
        System.out.println ("Error! Please enter y, Y, n, or N. Try again ");
    }
} while (true);

请注意,此方法正确处理所有输入,包括之前尚未定义输入时的第一个输入。

如果是一个无限循环(只要
sc.nextLine()
返回一些内容),用户只能输入“y”或“n”,则您没有描述要实现的目标:

while((choice = sc.nextLine()) != null) {
    if(choice.isEmpty()) {
        System.out.println("Error! This entry is required. Try again.");
    } else if(!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")) {
        System.out.println("Error! Please enter y, Y, n, or N. Try again.");
    } else {
        // do whatever you need
    }
}

@ScaryWombat
NOT(p或q)
在逻辑上等同于
NOT p AND NOT q
,这是Robby回答中使用的版本。@TimBiegeleisen True,但由于最初的调用不在OP提供的代码段中,所以我没有考虑它。如果我自己写的话,我会更接近你的版本。我没有把这个添加到我的答案中,因为我不想与你的答案重叠。
while(choice=sc.nextLine()){
不等同于布尔值
//做任何你需要的事情
加上
中断;
?oops,忘记了检查
null
。OP没有透露
sc
变量的性质,所以我使用了
sc.nextLine()
指的是扫描仪,如果没有更多行,它将返回
null
,从而中断循环。至于添加
break
,基于他的尝试,我假设他想要一个无限循环。