[英]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.