Search code examples
javawhile-loopbufferedreader

Why does the second while loop not get accessed at all after the first loop?


I created a nested while loop as shown in the image, however, after the first full loop is finished, the second while loop does not execute even though the condition inside the second while loop is still true. This could be an issue with System.in, but I tried commenting it out and it still did not loop again. What could be the issue here?

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

I have also included an image, which shows what exactly happens here. For the second time looping through, it should print out the schools but it does not.


Solution

  • You need to set variable j to 0 after exiting the loop.

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