개발/Java

[Java] 왼쪽으로 밀기 문제

suniverse 2023. 1. 13. 19:25

이 문제가 너무너무 안 풀려서 12일 새벽 4시까지 거진 5시간 정도 붙잡고 풀었다...

새벽에 친구랑 통화도 1시간 넘게 했다 ㅠㅠ

이 문제를 풀면서 느꼈던 점은 기초를 확실히 해둬야 한다는 점...

배열 자체는 이해를 했는데 for문에서 헛발짚고 있었다. 

디버깅의 소중함을 깨달았다......................

디버깅을 하지 않으면 어디서 문제가 생겼는지 알 수 없다. 

 

✍ 방법 1

public static void main(String[] args) { // 메인 메서드 시작
    int[] arr = {1, 2, 3, 4, 5};

    for(int i=0; i<arr.length; i++) {

        for(int j=0; j<arr.length; j++) {
            System.out.print(arr[j] + " ");
        }
        System.out.println();

        int tmp = arr[0];
        for(int j=0; j<arr.length-1; j++) {
            arr[j] = arr[j+1];
        }
        arr[arr.length-1] = tmp;
    }
} // 메인 메서드 끝

✍ 방법 2 (메서드 호출 사용) 

public class test1 {

	public static void main(String[] args) { // 메인 메서드 시작
		int[] arr = {1, 2, 3, 4, 5};
		
		for(int i=0; i<arr.length; i++) {
			printArray(arr); // printArray 메서드 호출 
			rotation(arr); // rotation 메서드 호출 
		}
	} // 메인 메서드 끝
	
	//리턴값x, 매개변수o 메서드
	public static void printArray(int[] arr) { // printArray 메서드 시작.
		for(int j=0; j<arr.length; j++) { // 배열 출력을 위한 반복문 
			System.out.print(arr[j] + " ");
		}
		System.out.println(); // 줄 바꿈 
		
	} // printArray 메서드 끝
	
	// 리턴값x, 메서드o 메서드 
	public static void rotation(int[] arr) { // rotation 메서드 시작
		int tmp = arr[0];
		for(int j=0; j<arr.length-1; j++) {
			arr[j] = arr[j+1];
		}
		arr[arr.length-1] = tmp;	
	} // rotation 메서드 끝 
	

}

 

💻