22.4.18 [HackerRank]Java End-of-file

์„œํƒœ์šฑยท2022๋…„ 4์›” 18์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
7/45
post-thumbnail
post-custom-banner

๐ŸŒฑ ๋ฐฐ๊ฒฝ์ง€์‹

EOF

End-of-file. ๋ฐ์ดํ„ฐ ์†Œ์Šค๋กœ๋ถ€ํ„ฐ ๋” ์ด์ƒ ์ฝ์„ ์ˆ˜ ์žˆ๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Œ์„ ๋‚˜ํƒ€๋‚ด๋Š” ์šฉ์–ด. Java์—์„œ ์•„๋ž˜์˜ ๋‘๊ฐ€์ง€ ๋ฐฉ์‹์œผ๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.

1) scanner.hasNext() : ์Šค์บ๋„ˆ ๊ฐ์ฒด๋กœ ์ž…๋ ฅ๊ฐ’์ด ๋“ค์–ด์˜ค๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•˜๋Š” ํ•จ์ˆ˜๋‹ค. hasNext๋’ค๋กœ Int, Double, Boolean ๋“ฑ์˜ ์ž๋ฃŒํ˜•์„ ๋ถ™์ด๋ฉด ์ž…๋ ฅ๊ฐ’์ด ๊ทธ ์ž๋ฃŒํ˜•์— ํ•ด๋‹นํ•  ๊ฒฝ์šฐ true ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์•„๋‹ˆ๋ฉด false ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

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

2) BufferedReader: scanner์™€ ๋‹ฌ๋ฆฌ EOF๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋‚ด์žฅํ•จ์ˆ˜๋Š” ์—†๋‹ค. ๋‹ค์Œ์˜ ์˜ˆ์‹œ์ฒ˜๋Ÿผ ์ฒ˜๋ฆฌํ•œ๋‹ค.

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

while((input = br.readLine()) != null) {
  // ์ดํ›„ ๋กœ์ง ์ „๊ฐœ.
}

Java While๋ฌธ

while (์กฐ๊ฑด๋ฌธ) {
    <์ˆ˜ํ–‰ํ•  ๋ฌธ์žฅ1>;
    <์ˆ˜ํ–‰ํ•  ๋ฌธ์žฅ2>;
    <์ˆ˜ํ–‰ํ•  ๋ฌธ์žฅ3>;
    ...
}

์กฐ๊ฑด๋ฌธ์ด ์ฐธ์ธ ๋™์•ˆ while๋ฌธ์˜ ์ˆ˜ํ–‰ํ•  ๋ฌธ์žฅ๋“ค์„ ๋ฐ˜๋ณตํ•ด์„œ ์ˆ˜ํ–‰ํ•œ๋‹ค.

โœ๏ธ ํ•ด์„ค ๋ฐ ๋ถ„์„

EOF์— ๋„๋‹ฌํ•  ๋•Œ ๊นŒ์ง€ stdin(System.in)์—์„œ ์•Œ ์ˆ˜ ์—†๋Š” n์ค„์˜ ์ž…๋ ฅ์„ ์ฝ๋Š”๋‹ค.
๊ฐ ์ค„์—๋Š” ์ค„ ๋ฒˆํ˜ธ์™€ ๊ณต๋ฐฑ ํ•˜๋‚˜๋ฅผ,๊ทธ๋ฆฌ๊ณ  ์ž…๋ ฅ๋ฐ›์€ content๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

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

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in); // ์ƒˆ ์Šค์บ๋„ˆ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ด ์ž…๋ ฅ๋ฐ›๋Š” ๊ฐ’(๋ฌธ์žฅ)์„ ๋ฐ›๋Š”๋‹ค.
        int i = 1; // ์ฒซ๋ฒˆ์งธ ์ค„์—์„œ 1๋ถ€ํ„ฐ ๋„˜๋ฒ„๋ง์ด ์‹œ์ž‘๋œ๋‹ค.
        while(sc.hasNext()){ // hasNext๋กœ ์ž…๋ ฅ๊ฐ’์ด ๋“ค์–ด์˜ค๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•ด ๋“ค์–ด์˜ค๋Š” ๊ฒฝ์šฐ๋ฅผ while๋ฌธ์˜ ์กฐ๊ฑด์œผ๋กœ ์ค€๋‹ค.
            System.out.println(i + " " + sc.nextLine()); //๋ฌธ์žฅ ์•ž์˜ ์ˆซ์ž + ๊ณต๋ฐฑ + ์ž…๋ ฅ๋ฐ›์€ ๋ฌธ์ž์—ด ์ „์ฒด๋ฅผ ๋ฆฌํ„ดํ•˜๊ธฐ ์œ„ํ•œ nextLine()ํ•จ์ˆ˜๋ฅผ ํ”„๋ฆฐํŠธํ•ด์ค€๋‹ค.
            i ++; // i๋Š” ํ•˜๋‚˜์”ฉ ์ฆ๊ฐ€ํ•ด ๋‚˜๊ฐ„๋‹ค. 
        }
    }
}

๐Ÿ‘‰ ์ฐธ๊ณ 

post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€