2013-08-06 118 views
1

有人可以帮我找出为什么while语句不工作?循环在i = 3之后停止,但如果continueSurvey = 0则不会停止。它会运行,但如果将continueSurvey更改为O,它将不会退出循环。即使我进入进程并且我可以看到变量是0,循环继续。虽然在多条件的Java循环

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++; 
       } 
      } 
    } 
} 

回答

0

的一部分,你问,如果用户想继续是这里面for循环

for (int row = a.getRespID(); row < 3; row++) 

不只是你的while循环。这意味着它会一直询问,直到for循环完成,只有当它终于回到while循环条件时才退出。

+0

谢谢!我最终在我的代码中放入了break语句。我尝试在for循环之外移动问题,但我需要它在下一个响应者生成之前提出问题。 –

+1

@MichelleAnderson是的,这可能是最有意义的解决方案:)请务必接受StormeHawke的回答,因为这可以帮助其他可能有类似问题的人。 – Jordan

-1

,如果你想退出循环,如果任一continueSurvey是0或I = 3 你写while循环是这样的:

while((continueSurvey != 0) || (i < 3)) { 
    ... 
} 

的& &(和)运营,标志着这两个条件都为了使循环退出而不是其中的一个(||或),才是真实的。

+1

不。如果continueSurvey为0且i = 2,则在您的示例中,条件将评估为true,这意味着它不会退出while循环。 &&表示如果它们中的任何一个都是假的,它将退出循环。 – Jordan

2

您需要在for循环中添加break。 IE,

if(continueSurvey == 0) 
    break; 

这将退出for循环,并允许while循环退出。

+1

谢谢! @StormeHawke –

+0

不客气!如果我的答案解决了您的问题,请考虑将其标记为已接受的答案(数字下方的复选标记) – StormeHawke

0

你在while循环条件是:

((continueSurvey != 0) && (i < 3)) 

这意味着在while循环的内块将当且仅当continuSurvey执行= 0并且在相同时刻i < 3!你有内部循环有不同的条件。我会使用调试器在内部循环中搜索问题。如果这个答案对你来说还不够,那么请说明你想达到什么目的。