본문 바로가기

알고리즘/Java

(JAVA)백준 단계별로 풀어보기 6단계 2562번 : 최댓값

배열

이번엔 1. Scanner+배열 /  2. Scanner+ 배열을 안쓰는 방법 /  3. BufferReader를 쓰는 방법 3가지를 사용했다.

 

소스 

 

1. Scanner + 배열

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Scanner;
public class Main{
    public static void main(String[]args){
        Scanner scan = new Scanner(System.in);
        int max = 0;
        int count = 0;
        int[] arr = new int[9];
        for(int i=0; i<arr.length; i++){
            arr[i]=scan.nextInt();
            if(max<arr[i]){
                 max = arr[i];
                 count = i+1;
             }
        }
       System.out.println(max);
       System.out.println(count);
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

최댓값을 max,  최댓값의 위치를 count로 지정.

 

2. Scanner + 배열x

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.Scanner;
public class Main{
    public static void main(String[]args){
        Scanner scan = new Scanner(System.in);
        int max = 0;
        int count = 0;
        for(int i=1; i<=9; i++){
            int a=scan.nextInt();
            if(max<a){
                 max = a;
                 count = i;
             }
        }
       System.out.println(max);
       System.out.println(count);
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

별 차는 없지만 배열 쓸 필요가 없다는게 보여서 써봄.

 

3.BufferReader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int max = 0;
        int count = 0;
        int[] arr = new int[9];
 
        for(int i = 0 ; i < 9 ; i++) {
            arr[i] = Integer.parseInt(br.readLine()); //BufferReader값은 String이므로  int 타입으로 변환
            if(max<arr[i]){
                 max = arr[i];
                 count = i+1;
             }
        }
        System.out.println(max);
        System.out.println(count);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
cs