2014-02-21 97 views
-3

在eclipse中我已經有了主要的方法(這裏沒有顯示)。該代碼將打印數組的特定循環

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

相反的兩個嵌套的循環,僅創建一個循環,從0days陣列的長度。在循環體中,打印daysmonths的相應元素。

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

嘗試運行這段代碼

for(i=0;i<days.length;i++) 
{ 
    System.out.println("days: " + days[i] + ", " + months[i]); 
} 
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]); 
}