在 Java 中使用 for 每个循环同时迭代两个数组 [英] Iterating over two arrays simultaneously using for each loop in Java
问题描述
学生的姓名(String[])和对应的标记(int[])存储在不同的数组中.
Student's names(String[]) and corresponding marks(int[]) are stored in different arrays.
如何在 Java 中使用 for 每个循环一起迭代两个数组?
How may I iterate over both arrays together using for each loop in Java ?
void list() {
for(String s:studentNames) {
System.out.println(s); //I want to print from marks[] alongside.
}
}
一种简单的方法是在同一个循环中使用索引变量.有什么好的办法吗?
One trivial way could be using index variable in the same loop. Is there a good way to do?
推荐答案
潜在的问题实际上是你应该将两个数组绑定在一起,并且只遍历一个数组.
The underlying problem is actually that you should tie both of the arrays together and iterate across just one array.
这是一个非常简单的演示 - 您应该使用 getter 和 setter,还应该使用 List
而不是数组,但这说明了这一点:
Here is a VERY simplistic demonstration - you should use getters and setters and you should also use a List
instead of an array but this demonstrates the point:
class Student {
String name;
int mark;
}
Student[] students = new Student[10];
for (Student s : students) {
...
}
这篇关于在 Java 中使用 for 每个循环同时迭代两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!