使用Java中的每个循环同时遍历两个数组 [英] Iterating over two arrays simultaneously using for each loop in Java

查看:584
本文介绍了使用Java中的每个循环同时遍历两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学生的姓名(字符串[])和相应的标记(INT [])存储在不同的数组。



如何迭代两个数组在Java中循环?

  void list(){

(String s:studentNames){
System .out.println(一个或多个); //我想打印标记[]旁边。




$ b $ p
$ b

一个简单的方法可能是使用index变量循环。有没有一个好的方法呢?解决方案

解决方案

实际上,你应该将两个数组绑在一起并遍历只是一个数组。



这是一个非常简单的演示 - 你应该使用getters和setter,你也应该使用 List

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆