본문 바로가기
코딩 공부방 👩‍💻👨‍💻/알고리즘

[Java] 해커랭크(HackerRank) : Java End-of-file

by ByJinnie 2023. 2. 5.
반응형

[문제] 

Scanner와 반복문을 연습하는 문제입니다. 여러 문장들을 입력하면, 각 문장이 숫자와 함께 출력돼야 합니다.

몇 개의 문장이 입력될지 모르기 때문에, hasNext() 메서드를 활용해야 합니다. 

hasNext()는 읽어올 요소가 남아있는지 확인하는 메서드이며, 요소가 남아있으면 true를, 없으면 false를 반환합니다.

 

예시)

입력값 :

Hello world
I am a file
Read me until end-of-file.

 

출력값:

1 Hello world
2 I am a file
3 Read me until end-of-file.

 

[코드]

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class hackerrank {

  public static void main(String[] args) {
    /*
     * Enter your code here. Read input from STDIN. Print output to STDOUT. Your
     * class should be named Solution.
     */

    // Declare variables
    int num = 1; // line number

    // Declare and create Scanner objects
    Scanner sc = new Scanner(System.in);
    
    // Use while loop for printing 
    while (sc.hasNext()) {
      String sentence = sc.nextLine();
      System.out.println(num + " " + sentence);
      // increase line number
      num++;
    }
  }
}

 

* 문제 출처 (Prepare > Java > Introduction > Java End-of-file)

: https://www.hackerrank.com/

 

HackerRank

HackerRank is the market-leading technical assessment and remote interview solution for hiring developers. Learn how to hire technical talent from anywhere!

www.hackerrank.com

 

반응형

댓글