프로그래밍 언어/Java

[Java] 입력(Scanner)

김꿍디꿍디 2024. 10. 31. 21:20
반응형

java에서는 Scanner 클래스를 사용하여 값을 입력받을 수 있다.

이를 통해서 정수, 실수, 단어, 줄단위를 쉽게 읽어올 수 있다.

공식 문서

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

 

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

 

import

import java.util.Scanner;

객체 생성

Scanner sc = new Scanner(System.in);

 

주의할 것은 Scanner 을 생성할 때 System.in 이 들어간다는 점이다.
System.in 은 사용자로부터 입력을 받기 위한 입력 스트림이다.

System.in 관련 참고할만한 글 : https://st-lab.tistory.com/41

 


주요 메소드

메소드명 반환 타입 설명
next() String 다음 토큰을 String 타입으로 반환 (띄어쓰기 뒷 부분은 읽지 않는다.)
nextLine() String 한 줄("\n (Enter)"를 치기 전까지)을 읽고, "\n (Enter)"값이 제외된 부분만을 출력한다.
nextInt() int 다음 토큰을 int 타입으로 반환한다.
nextShort() short 다음 토큰을 short 타입으로 반환한다.
nextLong() long 다음 토큰을 long 타입으로 반환한다.
nextFloat() float 다음 토큰을 float 타입으로 반환한다.
nextDouble() double 다음 토큰을 double 타입으로 반환한다.
nextBoolean() boolean 다음 토큰을 boolean 타입으로 반환한다.
nextByte() byte 다음 토큰을 byte 타입으로 반환한다.
hasNext() boolean 현재 입력된 토큰이 있으면 true를 반환한다.
혹은 새로운 입력이 들어올 때까지 기다려서, 새로운 입력이 들어오면 그 때 true를 반환한다.
ctrl + z 키가 입력되면 입력 끝이므로 false를 반환한다.
hasNextLine() boolean 다음에 읽을 값(Line 줄)이 있는지 확인한다.

주의할 점

next()와 nextLine()을 섞어서 사용할 경우

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        String str1 = sc.next();
        String str2 = sc.next();
        String str3 = sc.nextLine();
        String str4 = sc.nextLine();
        
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        
    }
}

 

next()는 개행 또는 공백을 입력받을 때 까지만 읽는다.

Cat\n
is\n
perfect\n

 

로 입력이 주어진 상황에서

str1에는 "Cat"이 저장되고 

str2에는 그 다음 개행 문자 전까지인 "\nis"가 저장된다. (\n는 출력 시 제외된다)

그래서 str3에는 "\n"이 저장되고, str4에는 "perfect"가 저장된다.  

 

이를 해결하기 위해서 next() 다음 nextLine() 입력 사이에 nextLine() 을 추가하는 방식을 사용한다.

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        String str1 = sc.next();
        String str2 = sc.next();
        sc.nextLine();
        String str3 = sc.nextLine();
        String str4 = sc.nextLine();
        
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        
    }
}

참고

https://st-lab.tistory.com/92

 

자바 [JAVA] - 스캐너(Scanner) 클래스와 입력

자바를 처음 배울 때 아마 대부분은 키보드로 입력받기 위해 Scanner 라는 클래스를 썼을 것이다. 자바 외에도 다양한 언어들은 각각의 입력방식이 있고, 각 언어별로 대표하는 대중적인 입력방식

st-lab.tistory.com

https://ssungkang.tistory.com/entry/java%EC%82%AC%EC%9A%A9%EC%9E%90%EB%A1%9C-%EB%B6%80%ED%84%B0-%EA%B0%92-%EC%9E%85%EB%A0%A5%EB%B0%9B%EA%B8%B0-Scanner

 

[java]사용자로 부터 값 입력받기, Scanner

Scanner 사용자로부터 값 입력 받기 java에서는 Scanner 클래스를 사용하여 값을 입력받을 수 있다. 이를 통해서 정수, 실수, 단어, 줄단위를 쉽게 읽어올 수 있다. Scanner 호출 import java.util.Scanner; Scanner

ssungkang.tistory.com

https://hstory0208.tistory.com/entry/Java%EC%9E%90%EB%B0%94-Scanner-%ED%81%B4%EB%9E%98%EC%8A%A4-%EC%9E%85%EB%A0%A5%EB%B0%9B%EA%B8%B0

 

[Java/자바] Scanner 클래스 (입력받기)

Scanner 클래스란? Scanner란 사용자로 부터 입력을 받을 수 있도록 도와주는 것으로, 간단한 예시를 보자면, 사용자가 게임에 로그인하기 위해, 아이디와 비밀번호를 입력하는 것과 같습니다. Scanner

hstory0208.tistory.com

 

반응형