循环遍历数组 - 只有第一个索引打印

时间:2013-12-04 11:58:57

标签: java arrays for-loop

我想遍历数组并打印任何非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();
  }
}

阵列:

static String[] studentNamesArray = new String[10];

问题是它只打印出index[0]。我该如何解决这个问题?

编辑:

这是我的完整代码:

  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");
    }
  }

3 个答案:

答案 0 :(得分:4)

仅使用for循环打印学生姓名。打印完所有学生后,请阅读studentChoice一次。否则在打印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();

答案 1 :(得分:1)

确保数组的内容不为null,否则它们不会打印出来

答案 2 :(得分:1)

我只能看到这里的原因,其他元素应该是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();// you need to check this 
     }else{
      System.out.println(i + ": " + studentNamesArray[i]);
     }
   }

可能还有其他原因。如果从input.nextInt()获取Scanner,您的程序将在那里等待用户输入。然后你必须提供输入才能继续。确保这些事情。