[英]else statement printing multiple times - array loop
我希望我的代码遍历数组,并且仅在数组中有值时才给用户一个删除学生的选项。 如果所有数组值都为null,那么我希望它打印出一条消息。 问题是我的消息为数组中的每个null元素多次打印。
我的代码:
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");
}
}
}
else
块在每个循环迭代中运行。 如果您只想在最后运行一次,请执行以下操作:
boolean studentFound = false;
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
...
然后在for
:
if (!studentFound) {
System.out.println("There are no students stored");
}
这是我将确定所有元素是否为空的方法。 您为每个null元素打印出来的原因是print语句位于for循环内。
boolean allNull = true; // default is that everything is null
for(int i = 0; i < studentNamesArray.length; i++) { // iterate through entire array
if(studentNamesArray[i] != null) { // if even 1 of them is not null
allNull = false; // set allNull to false
break; // and break out of the for loop
}
}
if(allNull) System.out.println("There are no students stored!");
在for
循环中,您使用相同的变量 i
,其中它覆盖了for循环中使用的原始变量。
尝试这样的事情:
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 (int j = studentChoice + 1;j < studentNamesArray.length; j++) {
studentNamesArray[j-1] = studentNamesArray[j];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(int k = studentChoice + 1;k < 9;k++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[k-1][y] = studentMarksArray[k][y];
}
}
markArrayCount = markArrayCount - 1;
for(int z = 0;z < 3;z++) {
studentMarksArray[9][z] = 0;
}
} else {
System.out.println("hi");
}
}
}
虽然我不确定您要打印的内容,但我还是根据自己的直觉对其他变量名称进行了调整; 结果可能与结果不完全相同,但是我敢肯定您可以对变量名进行进一步的调整,以免彼此重叠,也不会引起过多的循环。
我建议使用“布尔”变量,将其命名为“标志”。 将其初始化为“ false”。 如果在数组中未找到null元素,则设置'flag = true'。 在'for'循环之后,检查'if(!flag)System.out.println(“没有学生。”);'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.