我创建了一个嵌套的while循环,如image所示,但是,在第一个完整循环完成之后,即使第二个while循环中的条件仍然为true,第二个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,它显示了这里到底发生了什么。对于第二次遍历,它应该打印出学校,但不是。
答案 0 :(得分:0)
退出循环后,需要将变量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++;
}
答案 1 :(得分:0)
之所以不起作用,是因为一旦完成第一个完整循环(如您所述),j
就会变得比nStudents
大,这是因为您写了(j++;)
。永远不会第二次将其设置回0
或低于nStudents
,它会再次回到while
循环中。
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++;
}
答案 2 :(得分:0)
也可以使用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++;
}