如何解决为什么在第一个循环之后根本无法访问第二个while循环?
我创建了一个嵌套的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,它显示了这里到底发生了什么。对于第二次遍历,它应该打印出学校,但不是。
解决方法
退出循环后,需要将变量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
大,这是因为您写了(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++;
}
,
也可以使用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++;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。