-
[JAVA]자바 콘솔 입력 : Scanner 클래스Miscellaneous Dictionary 2022. 5. 24. 08:58
부트캠프 과정에서 자주 사용하게 되는 자바의 Scanner 클래스에 대해 알아보았다.
Scanner 클래스는 java.util 패키지에 존재한다. 따라서 사용을 위해서는 java.util 패키지를 import 해주어야 한다.
아래에서 Oracle 공식문서를 해석하며 살펴보도록 한다.
Scanner Class
A simple text scanner which can parse primitive types and strings using regular expressions.
정규식을 이용해 원시타입과 문자열을 파싱(=추출하여 가공하다)할 수 있는 간단한 텍스트 스캐너이다.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
스캐너는 입력된 텍스트를 구분자를 이용해 토큰들로 나누는데, 기본적인 구분자는 공백이다. 나눠진 토큰들은 다양한 next 메소드들을 통해 다양한 타입의 값으로 변환된다.
For example, this code allows a user to read a number from System.in:
예제를 보면, 아래 코드는 유저가 System.in 으로 들어온 숫자를 읽을 수 있다.
Scanner sc = new Scanner(System.in); int i = sc.nextInt();
As another example, this code allows long types to be assigned from entries in a file myNumbers:
다른 예제를 보면, 아래 코드는 myNumbers 파일에서 long 타입의 데이터들을 할당한다.
Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); }
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
Scanner는 공백이 아닌 다른 구분자를 사용할수도 있다. 아래 예제는 한 문자열에서 여러 요소들을 읽는다.
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close(); /* output 1 2 red blue */
여기까지 문서를 읽어보면 대략적인 Scanner 클래스의 역할과 동작을 알 수 있다. 물론 세세한 설정(예를 들면, 기본 구분자로 쓰이는 '공백'이 Character.isWhitespace() 를 이용한다는 것 등등..)들이 많지만 모두 알 필요는 없다. 필요한 경우 자세한 내용을 공식 문서에서 확인하여 사용하면 되기 때문이다. 여러가지 메소드들도 확인하여 사용해야겠다.
'Miscellaneous Dictionary' 카테고리의 다른 글
5/26 (0) 2022.05.26 5/25 (0) 2022.05.25 5/23 (선배 조언) (0) 2022.05.23 5/20 (0) 2022.05.21 5/19 (선배 조언) (0) 2022.05.20