数组的特定循环

时间:2014-02-21 10:55:16

标签: java arrays loops

我已经在eclipse中使用了main方法(此处未显示)。代码将打印

days 1: 5
days 1: 2
days 1: 6
days 2: 5
days 2: 2
days 2: 6
days 3: 5
days 3: 2
days 3: 6

如果我希望输出为

,代码应该是什么?
days 1: 5
days 2: 2
days 3: 6

代码:

int days[] = { 1, 2, 3 }; // each loop
int months[] = { 5, 2, 6 };

for (int i : days) {
    for (int g = 0; g < 3; ++g) {
        System.out.println("days: " + i + ", " + months[g]);
    }
}     

3 个答案:

答案 0 :(得分:3)

而不是两个嵌套循环,只创建一个循环,从0days数组的长度。在循环体中,打印daysmonths的相应元素。

for (int i = 0; i < days.length; i++) {
    // print days[i] together with months[i]
}

答案 1 :(得分:3)

int days[] = {1, 2, 3};     //each loop
int months[] = {5, 2, 6};   
for(int g = 0; g < days.length; g++)
{
  System.out.println("days: " + days[g] + ", " + months[g]);
}

答案 2 :(得分:1)

尝试运行此代码

for(i=0;i<days.length;i++)
{
    System.out.println("days: " + days[i] + ", " + months[i]);
}