[英]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.