【问题标题】:Why does the second while loop not get accessed at all after the first loop?为什么在第一个循环之后根本无法访问第二个 while 循环?
【发布时间】:2020-10-19 17:07:21
【问题描述】:

我创建了一个嵌套的 while 循环,如 image 所示,但是,在第一个完整循环完成后,即使第二个 while 循环内的条件仍然为真,第二个 while 循环也不会执行。这可能是System.in 的问题,但我尝试将其注释掉,但它仍然没有再次循环。这可能是什么问题?

int i = 0;
        int j = 0;
        int p = 0;
        
        
        while(i < nStudents) {
            p = i+1;
            System.out.println("\nStudent " + p + "'s rankings: ");
            
            while(j < nSchools) {
                
                System.out.print("\nSchool " + toArrayList.get(j).getName() + ": ");
                String ranking = DisplayMenu.br.readLine();
                Array1.add(ranking);
                
                j++;
            }
            i++;
        } 

我还包含了一个image,它显示了这里到底发生了什么。第二次循环,它应该打印出学校,但它没有。

【问题讨论】:

  • 这只是显示两个 while 循环及其打印内容的源代码。我将编辑问题以显示代码。
  • @PartialDifferentials 请务必提供可编译代码!!!
  • @oleg.cherednik 我会添加它,但它的 5 个源文件...
  • 请了解minimal reproducible example的概念。

标签: java while-loop bufferedreader


【解决方案1】:

退出循环后需要将变量j设置为0。

        int i = 0;
        int j = 0;
        int p = 0;
        int nStudents = 10;
        int nSchools = 4;            
        while (i < nStudents) {
            p = i + 1;
            System.out.println("\n Student " + p + "'s rankings: ");
            while(j<nSchools){
                System.out.print("\n School " + j+ " :");                   
                j++;
            }
            j=0; //// LIKE THIS
            i++;
        }

【讨论】:

    【解决方案2】:

    也可以使用for循环

    int i = 0;
            int nSchools = 4;
            for(int nStudents = 10; nStudents > i; i++){
                System.out.println("\n Student " + i + "'s rankings: ");
                for(int j = 0; j < nSchools; j++){
                    System.out.print("\n School " + j+ " :");
                }
                i++;
            }
    

    【讨论】:

      【解决方案3】:

      这不起作用的原因是,一旦第一个完整循环完成(就像你提到的那样),j 变得大于nStudents,因为你写了(j++;)。它永远不会在第二次回到while 循环时被设置回0 或低于nStudents

      int i = 0;
      int j = 0;
      int p = 0;
          
      while(i < nStudents) {
          p = i+1;
          System.out.println("\nStudent " + p + "'s rankings: ");
              
          while(j < nSchools) {
                  
              System.out.print("\nSchool " + toArrayList.get(j).getName() + ": ");
              String ranking = DisplayMenu.br.readLine();
              Array1.add(ranking);
                  
              j++;
          }
          //Set j less that nSchools here. One example is j = 0;
          i++;
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多