728x90

 

 

 

https://fall-in-dream.tistory.com/16

 

반복문 없이 배열 출력하기 ( Arrays.toString(arr))- JAVA

보통 배열을 출력하려고 하면 반복문을 사용하죠? 반복문을 사용한 출력 class Solution { public static void main(String args[]) throws Exception { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; // 배열 선언 for(int i = 0; i < arr.length

fall-in-dream.tistory.com

 

 

 

 

1차원 배열은 해결 완료!!!

 

그런데

2차원 배열을 출력할 때 Arrays.toString(arr); 을 사용하면 어떻게 될까요?

class Solution
{
	static Scanner sc = new Scanner(System.in);
	public static void main(String args[]) throws Exception
	{
		System.out.print(Arrays.toString(arr_test()));
	}
    
    public static int[][] arr_test()
    {
    	int[][] arr = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
    	return arr;
    }
}

 

결과물

 

[[I@74a14482, [I@1540e19d, [I@677327b6, [I@14ae5a5]

 

전에 함수에서 리턴한 배열을 그냥 출력하려고 할 때 나왔던 애들이 이제는 4개나!!!!

 

그러면 어떡해야 하느냐

 

Arrays.deepToString(출력하고 싶은 배열);

(참고, import java.util.Arrays; 필요합니다.)

 

class Solution
{
	static Scanner sc = new Scanner(System.in);
	public static void main(String args[]) throws Exception
	{
		System.out.print(Arrays.deepToString(arr_test()));
	}
    
    public static int[][] arr_test()
    {
    	int[][] arr = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
    	return arr;
    }
}

 

 

결과물

[[1, 2], [3, 4], [5, 6], [7, 8]]

 

글자가 조금 달라지자

이렇게 잘 출력되는 모습을 볼 수 있습니다.

2차원 배열 뿐만 아니라 다차원 배열도 사용 가능하니 편하게 사용해보세요!!

 

 

다음에 또 봐요

 

+ Recent posts