9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오.
예를 들어,
서로 다른 9개의 자연수 3, 29, 38, 12, 57, 74, 40, 85, 61
이 주어지면, 이들 중 최댓값은 85이고, 이 값은 8번째 수이다.
첫째 줄부터 아홉 번째 줄까지 한 줄에 하나의 자연수가 주어진다. 주어지는 자연수는 100 보다 작다.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[9];
int max = 0;
int max_index = 0;
for(int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
if(arr[i] > max) {
max = arr[i];
max_index = i;
}
}
System.out.println(max);
System.out.println(max_index + 1);
}
}
반복을 통해 배열에 값을 입력해준다.
동시에 if문을 통해 값을 비교해 max와 max_index에 값을 넣어준다.
import java.io.BufferedReader;
import java.io.inputStreamReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int max = 0;
int max_index = 0;
for(int i = 0; i < 9; i++) {
int value = Integer.parseInt(br.readLine());
if(value > arr) {
max = value;
max_index = i + 1;
}
}
System.out.println(max);
System.out.println(max_index);
}
}
BufferedReader
과 배열을 쓰지 않는 방식이다.
값 입력과 동시에 값을 비교하고 더 큰 값을 max에 담아 준다.