자바 기초/백준 예제

백준 2562번) 배열 최댓값 (자바) 오답노트

문에딕트 2021. 2. 12. 20:29

문제는 다음과 같다. 

 

내 첫번째 시도

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int [] score = new int [9];
		
		for(int i=0; i<score.length; i++) {
			score[i] = sc.nextInt();
		}
		
		int max = score[0];
		
		int index = 0;
		
		for(int i =1; i<score.length; i++) {
		
			if(score[i]>max) {
			max = score[i];
			index = i+1;
			}
		

		}
		
		System.out.println(max);
		System.out.println(index);
		
		
	}

}

 

틀렸다. 출력도 정확하게 되는데 왜 틀렸을까?

 

문제는 index 값이 였다. 

index 초기화를 0으로 해놨는데  만약 score[0]이 최댓값이라  if 문 안에 들어갈 일이 없다면 index는 0으로 출력될 것이다. 

 

최댓값이 몇번째 수 인지를 출력해야 함으로, index 초기화를 1로 해준다면  score[0]이 최댓값이라도 index는 1을 출력, 즉 첫번째 수라는 것을 말해주기 때문에 정답이 된다.

 

그래서 

정답

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int [] score = new int [9];
		
		for(int i=0; i<score.length; i++) {
			score[i] = sc.nextInt();
		}
		
		int max = score[0];
		
		int index = 1;
		
		for(int i =1; i<score.length; i++) {
		
			if(score[i]>max) {
			max = score[i];
			index = i+1;
			}
		

		}
		
		System.out.println(max);
		System.out.println(index);
		
		
	}

}