๊ธ€ ์ž‘์„ฑ์ž: ์ด์ง€์›๐ŸŒฉ๏ธ

#10951

#10950 ๊ณผ ๋‹ฌ๋ฆฌ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ๊ฐœ์ˆ˜๋ฅผ ์ฃผ์ง€ ์•Š์•„์„œ ๋ฌธ์ œ ํ‘ธ๋Š”๋ฐ ํ—ค๋ฉจ๋‹ค. ์ฒ˜์Œ์—๋Š” while(true)๋ฅผ ์ฃผ์–ด์„œ ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๊ฐ€ ๋–ด์—ˆ๋‹ค. ๊ทธ๋ž˜์„œ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋ฅผ 100๊ฐœ ์ฃผ๊ณ  ๋Œ๋ฆฌ๋ฉด ๋˜์ง€ ์•Š์„๊นŒ? ํ–ˆ์ง€๋งŒ ๊ฒฐ๊ณผ๋Š” ์‹คํŒจโ€ฆ.

์‚ฝ์งˆ์ฝ”๋“œ 1

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        int a, b;
        Scanner in = new Scanner(System.in);

        while (true) {
            a = in.nextInt();
            b = in.nextInt();
            System.out.println(a + b);
        }
    }
}

์‚ฝ์งˆ์ฝ”๋“œ 2

import java.util.*;
public class Main{
    final static int MAX = 100;

    public static void main(String[] args) {
        int a, b;
        Scanner in = new Scanner(System.in);

        for(int i=0; i < MAX; i++) {
            a = in.nextInt();
            b = in.nextInt();
            System.out.println(a+b);
        }
    }
}

๊ฒ€์ƒ‰์„ ํ•ด๋ณด๋‹ˆ, EOF(End of File) - ๋ฐ์ดํ„ฐ ์†Œ์Šค๋กœ๋ถ€ํ„ฐ ๋” ์ด์ƒ ์ฝ์„ ์ˆ˜ ์žˆ๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Œ๊ฐ€ ๋ฐ˜ํ™˜๋  ๋•Œ๊นŒ์ง€ ๋ฃจํ”„๋ฅผ ๋Œ๋ ค์ฃผ๋ฉด ๋œ๋‹ค๊ณ  ํ•œ๋‹ค. C์–ธ์–ด์˜ ๊ฒฝ์šฐ!= EOF ๋กœ ํƒˆ์ถœํ•œ๋‹ค. Java๋Š” ์–ด๋–ป๊ฒŒ ํƒˆ์ถœํ•˜๋Š” ์ง€ ๊ฒ€์ƒ‰ํ•ด๋ดค๋Š”๋ฐ, Scanner๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ hasNextInt() ๋ฉ”์†Œ๋“œ๋ฅผ ์ด์šฉํ•œ๋‹ค. intํ˜• ๋ฐ์ดํ„ฐ๊ฐ€ ์˜ค๋ฉด true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ , ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ์ค‘๊ฐ„์— ๋ฌธ์ž์—ด์„ ์‚ฝ์ž…ํ–ˆ์„ ๊ฒฝ์šฐ while(hasNextInt())์˜ ๊ฒฝ์šฐ ์˜ค๋ฅ˜์—†์ด ์ข…๋ฃŒ๋˜๋Š” ๋ฐ˜๋ฉด์—, while(true)๋Š” java.util.InputMismatchException ์—๋Ÿฌ๊ฐ€ ๋‚˜์˜ค๋ฉด์„œ ์ข…๋ฃŒ๋œ๋‹ค.

import java.util.Scanner;

public class BOJ10951 {

    public static void main(String[] args) {
        int a, b;
        Scanner in = new Scanner(System.in);

        while(in.hasNextInt()) {
            a = in.nextInt();
            b = in.nextInt();
            System.out.println(a+b);
        }
    }
}
๋ฐ˜์‘ํ˜•