为什么在第一个循环之后根本无法访问第二个 while 循环?
Why does the second while loop not get accessed at all after the first loop?
我创建了一个嵌套的 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,它显示了这里究竟发生了什么。第二次循环,它应该打印出学校但没有。
退出循环后需要将变量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++;
}
这不起作用的原因是,一旦第一个完整循环完成(如您所提到的),j
变得大于 nStudents
因为您写了 [=13] =].它永远不会设置回 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++;
}
也可以使用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++;
}
我创建了一个嵌套的 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,它显示了这里究竟发生了什么。第二次循环,它应该打印出学校但没有。
退出循环后需要将变量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++;
}
这不起作用的原因是,一旦第一个完整循环完成(如您所提到的),j
变得大于 nStudents
因为您写了 [=13] =].它永远不会设置回 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++;
}
也可以使用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++;
}