재귀 함수, 정렬

boseung·2023년 9월 10일
0

재귀함수를 이용한 최댓값

재귀함수를 이용한 최댓값

간단한 문제인데, 재귀함수로 바꿔서 푸니까 조금 고민했다.

그리고 클래스에 필드 변수를 사용해서 접근하다가 에러가 발생했는데,

error: non-static variable max cannot be referenced from a static context

non-static 변수가 static context에 있는 변수를 참조하려고 해서 에러가 발생했다는 것이다.

간단히 말하면 non-static 변수는 인스턴스 생성 시 사용될 수 있고, static 변수는 클래스 로딩 후부터 생성되는데, 이렇게 생성 시점이 다르기 때문에 에러가 생긴 것이다.

public class Main {
    public static int max = -1;

    public static void main(String[] args) {
        int[] arr = new int[100];
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        findMax(n, arr);
        System.out.println(max);
    }

    public static void findMax(int n, int[] arr) {
        if (n == 0) return;
        if (max < arr[n-1]) max = arr[n-1];
        findMax(n - 1, arr);
    }
}

이렇게 static 변수로 선언해주어서 에러가 해결되었다.

해설 풀이는 배열을 static으로 선언해서 접근했다.

public class Main {    
    public static final int MAX_N = 100;
    
    public static int[] arr = new int[MAX_N];
    // ...
}

숫자정렬

숫자정렬

자바로 숫자 정렬하는 방법은 알고 있긴 했는데, int 배열의 내림차순 정렬은 Integer로 바꿔줘야만 할 수 있다는 것은 처음 알게 되었다.

정렬은 많이 사용하니까 잘 기억해둘 필요가 있을 것 같다.

특히 스트림으로 boxing 과정을 통해 Integer로 전환하는 것은 좀 잊어먹은 거 같아서 연습을 해둬야 할 것 같다.

int[] arr = new int[n];
//... 
Integer arr2[] = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(arr2, Collections.reverseOrder());
profile
Dev Log

0개의 댓글

관련 채용 정보