๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป ์ฝ”๋”ฉํ…Œ์ŠคํŠธ/๋ฐฑ์ค€

[๋ฐฑ์ค€/Java] 10951 A+B - 4 : EOF๋ž€?

by ๋ฝ€์งœ๊ผฌ 2025. 1. 17.
728x90
๋ฐ˜์‘ํ˜•

 

์ž…๋ ฅ์ด ๋๋‚  ๋•Œ๊นŒ์ง€ A+B๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ. EOF์— ๋Œ€ํ•ด ์•Œ์•„ ๋ณด์„ธ์š”.

๋ฌธ์ œ

๋‘ ์ •์ˆ˜ A์™€ B๋ฅผ ์ž…๋ ฅ๋ฐ›์€ ๋‹ค์Œ, A+B๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ

์ž…๋ ฅ์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.

๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ํ•œ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ๊ฐ ์ค„์— A์™€ B๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (0 < A, B < 10)

1 1
2 3
3 4
9 8
5 2

์ถœ๋ ฅ

๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋งˆ๋‹ค A+B๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

2
5
7
17
7

 

๋ฌธ์ œ๋ฅผ ๋‹ค์‹œ ๋ณด์ž.

์ž…๋ ฅ์ด ๋๋‚  ๋•Œ๊นŒ์ง€ A+B๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ. EOF์— ๋Œ€ํ•ด ์•Œ์•„ ๋ณด์„ธ์š”.

EOF๊ฐ€ ๋ญ์ž„?

( = End of File )
: ๋ฐ์ดํ„ฐ ์†Œ์Šค๋กœ๋ถ€ํ„ฐ ๋” ์ด์ƒ ์ฝ์„ ์ˆ˜ ์žˆ๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Œ์„ ๋‚˜ํƒ€๋‚ด๋Š” ๋ง์ด๋‹ค.

๊ทธ๋Ÿฌ๋‹ˆ๊นŒ ์ž…๋ ฅ์ด ๋๋‚  ๋•Œ = ์ฝ์„ ์ˆ˜ ์žˆ๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์„๋•Œ

์ด๋ฏ€๋กœ, EOF๋ฅผ ์ด์šฉํ•ด์„œ ํ’€์–ด์•ผํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

 

โœ”๏ธ Scanner ํด๋ž˜์Šค์—์„œ์˜ EOF

- hasNext() ๋ฉ”์†Œ๋“œ ์‚ฌ์šฉํ•˜๊ธฐ

์ž…๋ ฅ๋œ ํ† ํฐ์ด ์žˆ์œผ๋ฉด true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์„ ๊ฒฝ์šฐ false ๋ฐ˜ํ™˜

Scanner scanner = new Scanner(System.in);
		
while(scanner.hasNext()) {
  System.out.println(scannner.nextLine());
}

scanner.close();

 

โœ”๏ธ BufferedReader ํด๋ž˜์Šค์—์„œ์˜ EOF

- ๋”ฐ๋กœ ๋‚ด์žฅ๋œ ํ•จ์ˆ˜๊ฐ€ ์—†๋‹ค.

readLine()์ด null์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด EOF์— ๋„๋‹ฌํ–ˆ์Œ์„ ์˜๋ฏธํ•œ๋‹ค.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str ="";

while((str = br.readLine()) != null) {
  // ๋กœ์ง ์ ์œผ๋ฉด๋ฉ๋‹ˆ๋‹ค
  System.out.println(str);
}

 

์ฝ์€ ๊ฐ’์ด null์ด ๋˜๋ฉด ๋ฐ˜๋ณต๋ฌธ์„ ์ข…๋ฃŒํ•œ๋‹ค.

 


 

โœ๏ธ ํ’€์ด

import java.io.*;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        String str;

        while ((str = br.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(str);
            int A = Integer.parseInt(st.nextToken());
            int B = Integer.parseInt(st.nextToken());
            bw.write(A+B+"\\n");
        }
        bw.flush();
        bw.close();
        br.close();
    }
}

 

๋ฐฑ์ค€์ฒ˜๋Ÿผ ํŒŒ์ผ์„ ์ฝ์–ด์˜ค๋Š” ๊ฒฝ์šฐ, EOF๊ฐ€ ๋ฐœ์ƒ๋˜์ง€๋งŒ,

IDE์—์„œ EOF๋ฅผ ์ผ์œผํ‚ค๋ ค๋ฉด

  • Windows: Ctrl + Z + Enter
  • Linux/macOS: Ctrl + D

 

๋ฅผ ์ž…๋ ฅํ•ด์ค˜์•ผํ•œ๋‹ค.

 

๊ทธ๋Ÿฌ๋ฉด IDE์—์„œ๋„ ์œ„์˜ ์ฝ”๋“œ๊ฐ€ ์ •์ƒ ์ž‘๋™ํ•จ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•