使用Java中的每个循环同时迭代两个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19318707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating over two arrays simultaneously using for each loop in Java
提问by Tanay
Student's names(String[]) and corresponding marks(int[]) are stored in different arrays.
学生的姓名(String[]) 和相应的标记(int[]) 存储在不同的数组中。
How may I iterate over both arrays together using for each loop in Java ?
如何使用 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?
一种简单的方法可能是在同一个循环中使用索引变量。有什么好办法吗?
采纳答案by OldCurmudgeon
The underlying problem is actually that you should tie both of the arrays together and iterate across just one array.
潜在的问题实际上是您应该将两个数组联系在一起并仅遍历一个数组。
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:
这是一个非常简单的演示 - 您应该使用 getter 和 setter,并且还应该使用 aList
而不是数组,但这说明了这一点:
class Student {
String name;
int mark;
}
Student[] students = new Student[10];
for (Student s : students) {
...
}
回答by dasblinkenlight
You need to do it using the regular for
loop with an index, like this:
您需要使用for
带有索引的常规循环来执行此操作,如下所示:
if (marks.length != studentNames.length) {
... // Something is wrong!
}
// This assumes that studentNames and marks have identical lengths
for (int i = 0 ; i != marks.length ; i++) {
System.out.println(studentNames[i]);
System.out.println(marks[i]);
}
A better approach would be using a class to store a student along with his/her marks, like this:
更好的方法是使用类来存储学生及其分数,如下所示:
class StudentMark {
private String name;
private int mark;
public StudentMark(String n, int m) {name=n; mark=m; }
public String getName() {return name;}
public int getMark() {return mark;}
}
for (StudentMark sm : arrayOfStudentsAndTheirMarks) {
System.out.println(sm.getName());
System.out.println(sm.getMark());
}
回答by Maxim Shoustin
If them both have the same size, I would write:
如果它们的大小相同,我会写:
for(int i = 0; i<marks.length; i++) {
String names= studentNames[i]
int mark = marks[i];
}
回答by Isaac Buziba
The other way is to use a verbose for loop statement such as;
另一种方法是使用冗长的 for 循环语句,例如;
int i,j;
for(i = 0, j=0; i<= student.length-1 && j <=grades.length-1; i++,j++)
{
...
}