Three ways to print Java arrays

1. Three ways of outputting an array

One-dimensional array:

define an array int[] array = {1,2,3,4,5};

(1) The traditional for loop method

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

 

(2) for each loop

for(int a:array)
    System.out.println(a);


(3) Use the toString method in the Array class

 

Calls Array.toString(a), which returns a string containing the elements of the array, enclosed in parentheses and separated by commas

int[] array = {1,2,3,4,5};
System.out.println(Arrays.toString(array));

Output: [1, 2, 3, 4, 5]

 

Description: System.out.println(array); This is not possible, so printing is the first address of the array.

 

Two-dimensional array:

For two-dimensional arrays, these three methods are also corresponding, define a two-dimensional array:

 int[][]magicSquare =
    	 {
    		 {16,3,2,13},
    		 {5,10,11,8},
    		 {9,6,7,3}
    	 };

Java does not actually have multi-dimensional arrays, only one-dimensional arrays. Multi-dimensional arrays are interpreted as "arrays of arrays". For example, a two-dimensional array magicSquare is a three-element array containing {magicSquare[0], magicSquare[1], magicSquare[2]}. Dimensional array, magicSqure[0] is a one-dimensional array containing four elements {16,3,2,13}, the same is true for magicSquare[1] and magicSquare[2] .

(1) The traditional for loop method

for(int i=0;i<magicSquare.length;i++)
     {
    	 for(int j=0;j<magicSquare[i].length;j++)
    	 {
    		 System.out.print(magicSquare[i][j]+" ");
    	 }
    	 System.out.println();	//换行
     }

 


(2) for each loop

 

for(int[] a:magicSquare)
     {
    	 for(int b:a)
    	 {
    		 System.out.print(b+" ");
    	 }
    	 System.out.println();//换行
     }


(3) Use the toString method in the Array class

for(int i=0;i<magicSquare.length;i++)
    System.out.println(Arrays.toString(magicSquare[i]));

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324090796&siteId=291194637