使用Java中的每个循环同时迭代两个数组


问题内容

学生的姓名(String [])和相应的标记(int [])存储在不同的数组中。

如何使用Java中的每个循环一起遍历两个数组?

void list() {

    for(String s:studentNames) {
        System.out.println(s); //I want to print from marks[] alongside.
    }
}

一种简单的方法是在同一循环中使用索引变量。有什么好办法吗?


问题答案:

潜在的问题实际上是您应该将两个数组绑定在一起,并且仅跨一个数组进行迭代。

这是一个非常简单的演示-您应该使用getter和setter,还应该使用a List而不是数组,但这证明了这一点:

class Student {
  String name;
  int mark;
}
Student[] students = new Student[10];

for (Student s : students) {
  ...
}