HackerRank/JAVA

Java Stdin and Stdout I

예쁜꽃이피었으면 2024. 1. 12. 08:50

https://www.hackerrank.com/challenges/java-stdin-and-stdout-1/problem?isFullScreen=true

 

Java Stdin and Stdout I | HackerRank

Get started with standard input and output.

www.hackerrank.com

import java.util.*;

 

public class Solution {

 

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

       

        while (scan.hasNext()) {

            int a = scan.nextInt();

            System.out.println(a);

        }

        

    }

}

 

 

 


Scanner 

 

1. 사용자에게 입력값을 받올 때 사용한다.

2. 패키지 : java.util.Scanner

3. 객체 생성 :  Scanner sc = new Scanner(System.in);

- System.in : byte단위로 읽음

- 공백이나 줄바꿈을 기준으로 읽어들이는데, 

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

와 같이 필요한 구문자를 만들어서 사용할 수도 있다.

4. 자주 사용하는 메소드

close() 스캐너 객체 종료
hasNext() 공백을 기준으로 다음 입력값이 있는지 확인
hasNextLine() 줄바꿈을 기준으로 다음 입력값이 있는지 확인
nextInt() int형 입력값 리턴
nextDouble() Double형 입력값 리턴

 

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNextByte-int-

 

Scanner (Java Platform SE 8 )

Scans the next token of the input as a float. This method will throw InputMismatchException if the next token cannot be translated into a valid float value as described below. If the translation is successful, the scanner advances past the input that match

docs.oracle.com

 

 

 

 

 

더보기

Most HackerRank challenges require you to read input from stdin (standard input) and write output to stdout (standard output).

One popular way to read input from stdin is by using the Scanner class and specifying the Input Stream as System.in. For example:

Scanner scanner = new Scanner(System.in);
String myString = scanner.next();
int myInt = scanner.nextInt();
scanner.close();

System.out.println("myString is: " + myString);
System.out.println("myInt is: " + myInt);

The code above creates a Scanner object named  and uses it to read a String and an int. It then closes the Scanner object because there is no more input to read, and prints to stdout using System.out.println(String). So, if our input is:

Hi 5

Our code will print:

myString is: Hi
myInt is: 5

Alternatively, you can use the BufferedReader class.

Task
In this challenge, you must read  integers from stdin and then print them to stdout. Each integer must be printed on a new line. To make the problem a little easier, a portion of the code is provided for you in the editor below.

Input Format

There are  lines of input, and each line contains a single integer.

Sample Input

42
100
125

Sample Output

42
100
125

 

반응형

'HackerRank > JAVA' 카테고리의 다른 글

Java Loops I  (0) 2024.01.12
Java Output Formatting  (0) 2024.01.12
Java Stdin and Stdout II  (0) 2024.01.12
Java If-Else  (0) 2024.01.12
Welcome to Java!  (0) 2024.01.12