简体   繁体   中英

Iterate over a 2D array in Java

I am very new in java and I was wondering is there any way to avoid to hardcode the "4" on the second for loop? thanks

 public class Test {   public static void main(String[] args){
         double [][] array2D = {{1,2,3,4},{10,11,12,13},{100,101,102,103}};
         for(int i = 0 ; i < array2D.length ; i++){
           for(int j = 0 ; j < 4 ; j++){
             System.out.println(array2D[i][j]);
         } } } }

If you have a jagged 2D array the answer in the comment section works

for (int i=0; i< array2D.length; i++) 
{ 
    for (int j=0; j< array2D[i].length; j++) 
        System.out.println(array2D[i][j]);
} 

if you have a 2D array where the number of columns is constant

for (int i=0; i< array2D.length; i++) 
{ 
    for (int j=0; j< array2D[0].length; j++) 
        System.out.println(array2D[i][j]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM