728x90
문제
https://www.acmicpc.net/problem/2562
2562번: 최댓값
9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오. 예를 들어, 서로 다른 9개의 자연수 3, 29, 38, 12, 57, 74, 40, 85, 61 이 주어
www.acmicpc.net
9개의 수를 입력받은 뒤, 이 중에서 최댓값과 최댓값이 몇 번째 수인지 구하는 문제이다.
입력 출력
3 85
29 8
38
12
57
74
40
85
61
------------------------------------------------------------------------------------------------------------------
풀이
값을 비교할 변수 max를 초기화해 준 다음, 배열 값과 비교하여 max값을 바꾸어준다.
바뀐 max 값이 몇 번째 배열에 위치하는지 알기 위해 index + 1을 해주었다.
(1) Scanner 사용
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int array1[] = new int[9];
int max = 0;
int index = 0;
for(int i=0;i<array1.length;i++) {
array1[i] = sc.nextInt();
if(array1[i]>max) {
max = array1[i];
index = i+1;
}
}
sc.close();
System.out.println(max);;
System.out.println(index);
}
}
------------------------------------------------------------------------------------------------------------------
(2) BufferdReader 사용
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int array1[] = new int[9];
int max = 0;
int index = 0;
for(int i=0;i<array1.length;i++) {
array1[i] = Integer.parseInt(br.readLine());
if(array1[i]>max) {
max = array1[i];
index = i+1;
}
}
br.close();
System.out.println(max);;
System.out.println(index);
}
}
728x90
'문제 풀이' 카테고리의 다른 글
[백준] 10813번: 공 바꾸기 - JAVA (자바) (0) | 2023.05.06 |
---|---|
[백준] 10810번: 공 넣기 - JAVA (자바) (0) | 2023.05.05 |
[백준] 10818번: 최소, 최대 - JAVA (자바) (0) | 2023.02.13 |
[백준] 10871번: X보다 작은 수 - JAVA (자바) (0) | 2023.02.10 |
[백준] 10807번: 개수 세기 - JAVA (자바) (0) | 2023.02.06 |