[英]looping through array - only first index printing
I want to loop through an array and print any values that are not null, here is the code I am trying to use: 我想遍历一个数组并打印任何不为null的值,这是我尝试使用的代码:
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
}
}
Array: 阵:
static String[] studentNamesArray = new String[10];
The problem is that it is only printing out index[0]
. 问题在于它仅打印出index[0]
。 How can I fix this? 我怎样才能解决这个问题?
EDIT: 编辑:
Here is my full code: 这是我的完整代码:
static void deleteStudent() {
boolean studentFound = false;
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
for (i = 0; i < 10; i++) {
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;
}
}
}
if (!studentFound) {
System.out.println("There are no students stored");
}
}
Use the for-loop only to print the students names. 仅使用for循环打印学生姓名。 And read the studentChoice
once after you printed all the students. 打印studentChoice
所有学生后,阅读一次studentChoice
。 Otherwise it waits for input after printing the studentNamesArray[0]
否则,在打印studentNamesArray[0]
之后等待输入
System.out.println("Which student would you like to delete?");
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println(i + ": " + studentNamesArray[i]);
}
}
int studentChoice = input.nextInt();
确保数组的内容不为空,否则它们不会打印出来
Only reason I can see here, other elements should be null
. 我在这里看到的唯一原因是,其他元素应该为null
。 You can make sure it as follows 您可以确保如下
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();// you need to check this
}else{
System.out.println(i + ": " + studentNamesArray[i]);
}
}
But may be there is another reason. 但是可能还有另一个原因。 If input.nextInt()
is take from Scanner
, your program will wait there for a user input. 如果input.nextInt()
来自Scanner
,则程序将在那里等待用户输入。 Then you have to provide that input to continue. 然后,您必须提供该输入才能继续。 Make sure those things. 确保这些东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.