[英]While loop in Java with Multiple conditions
有人可以帮我弄清楚为什么while语句不起作用吗? 循环在i = 3之后不会停止,但是如果continueSurvey = 0则不会停止。它会运行,但是如果我将continueSurvey更改为O,它将不会退出循环。即使我进入进程,也可以看到变量为0,循环继续。
import java.util.Scanner;
public class SurveyConductor
{
public static void main(String[] args)
{
Survey a = new Survey();
a.display();
a.enterQuestions();
int continueSurvey = 1;
int i = 0;
while ((continueSurvey != 0) && (i < 3))
{
for (int row = a.getRespID(); row < 3; row++)
{
System.out.println("Respondent " + (row+1) + " Please tell us how you would rate our: ");
for (int col = 0; col < 3; col++)
{
Scanner input = new Scanner(System.in);
System.out.println(a.presentQuestion(col) + ": ");
System.out.println("Enter your response (1-Strongly Disagree, 2-Disagree, 3-Neutral, 4-Agree, 5-Strongly Agree): ");
int response = input.nextInt();
if ((response < 1) || (response >5))
{
while ((response < 1) || (response > 5))
{
System.out.println("Your response must be between 1 and 5. Please try again.");
System.out.println(a.presentQuestion(col) + ": ");
System.out.println("Enter your response (1-Strongly Disagree, 2-Disagree, 3-Neutral, 4-Agree, 5-Strongly Agree): ");
response = input.nextInt();
}
}
a.logResponse(row,col,response);
System.out.println();
}
a.displaySurveyResults();
System.out.println();
System.out.println("The top rated question is Question #" + a.topRatedQuestion() + ".");
System.out.println("The bottom rated question is Question #" + a.bottomRatedQuestion() + ".");
System.out.println();
Scanner input2 = new Scanner(System.in);
System.out.println("Are there any more repondents (0 - No, 1 - Yes): ");
continueSurvey = input2.nextInt();
a.generateRespondentID();
i++;
}
}
}
}
您需要在for
循环中添加一个break
。 IE浏览器,
if(continueSurvey == 0)
break;
这将退出for
循环,并允许while
循环退出。
您询问用户是否要继续的部分在此for循环内
for (int row = a.getRespID(); row < 3; row++)
不只是您的while循环。 这意味着它将一直询问直到for循环完成,仅在最终回到while循环条件时才退出。
while循环中的条件是:
((continueSurvey != 0) && (i < 3))
这意味着,当且仅当continueSurvey!= 0并且i <3同时执行时,才会执行while循环的内部块。 您有具有不同条件的内部循环。 我会使用调试器在内部循环中搜索问题。 如果这个答案对您来说还不够,请说明您要达到的目标。
如果您要退出循环(如果continueSurvey为0或i = 3),则必须编写while循环,如下所示:
while((continueSurvey != 0) || (i < 3)) {
...
}
&&(和)运算符表示两个条件都必须为真,以使循环不退出其中一个条件(||或)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.