java else语句打印多次数组循环
我希望我的代码在数组中循环,并且仅当数组中有值时,才允许用户选择删除学生。如果所有数组值都为空,那么我希望它打印出一条消息。问题是,对于数组中的每个空元素,我的消息会打印多次
我的代码:
static void deleteStudent() {
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
for (i = studentChoice + 1;i < studentNamesArray.length; i++) {
studentNamesArray[i-1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(i = studentChoice + 1;i < 9;i++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[i-1][y] = studentMarksArray[i][y];
}
}
markArrayCount = markArrayCount - 1;
for(int y = 0;y < 3;y++) {
studentMarksArray[9][y] = 0;
}
} else {
System.out.println("There are no students stored");
}
}
}
# 1 楼答案
下面是我如何确定所有元素是否都为null的方法。您为每个null元素打印它的原因是print语句位于for循环内
# 2 楼答案
在
for
循环中,使用相同的变量i
,它覆盖for循环中使用的原始变量试试这样:
虽然我不确定你想打印什么,但我根据直觉对其他变量名进行了调整;结果可能与结果不完全一样,但我相信您可以对变量名进行进一步调整,这样就不会过度使用彼此,导致过多循环
# 3 楼答案
else
块在每个循环迭代中运行。如果希望在最后只运行一次,请执行以下操作:然后在
for
之后: