전공/JAVA
JAVA 키보드 입력 read(), skip() 사용법
무한공백
2009. 8. 27. 15:35
ystem.in 에 있는 read()의 사용법은
System.in.read() ; 해주면 된다.
read()는 키보드로부터 들어오는 아스키 값을 가지므로, 아래와 같이 사용한다.
예를 들어 정수형 숫자를 입력한다고 한다면,
int x = System.in.read() - '0' ;
문자형을 입력할 때는
char x = (char)System.in.read();
read는 한 문자만을 입력받으므로, 버퍼로 인해서 예상치 못한 경우가 발생할 수 있다.
아래의 경우를 보자.
연속해서 두번, 또는 그 이상의 문자를 입력받는 경우에는
반듯이 skip함수를 써서 버퍼에 쌓인 개행 문자를 버리도록 한다.
다른 방법으로 아래와 같이 할 수도 있다.
BufferedReader 를 선언한 후 readLine 해버리는 방식도 있다.
Skip 함수 설명
skip
public long skip(long n)
throws IOException
- Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached.
-
- Parameters:
n
- The number of characters to skip- Returns:
- The number of characters actually skipped
- Throws:
IllegalArgumentException
- Ifn
is negative.IOException
- If an I/O error occurs
반환형은 실제 스킵된 문자 개숫
파라미터는 스킵할 숫자 갯수를 적어준다.