使用Java中的每个循环同时遍历两个数组 [英] Iterating over two arrays simultaneously using for each loop in Java
问题描述
如何迭代两个数组在Java中循环?
void list(){
(String s:studentNames){
System .out.println(一个或多个); //我想打印标记[]旁边。
$ b $ p
$ b 一个简单的方法可能是使用index变量循环。有没有一个好的方法呢?解决方案
解决方案
实际上,你应该将两个数组绑在一起并遍历只是一个数组。
这是一个非常简单的演示 - 你应该使用getters和setter,你也应该使用 List $ c $而不是一个数组,但是这表明了这一点:
class Student {
String name;
int mark;
}
Student [] students = new Student [10];
(学生s:学生){
...
}
Student's names(String[]) and corresponding marks(int[]) are stored in different arrays.
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.
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中的每个循环同时遍历两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!