Scanner
는 Java에서 텍스트 입력을 읽고 분석하기 위한 도구로,java.util.Scanner
패키지에 포함되어 있습니다. 이를 통해 키보드 입력, 파일 데이터, 문자열 등의 다양한 입력 소스를 간단히 처리할 수 있습니다.
다양한 입력 소스를 처리할 수 있음 :
System.in
)new File("example.txt")
)new String("42 3.14 Hello")
)데이터를 토큰(token) 단위로 분리하여 읽음.
다양한 데이터 타입의 값을 읽음:
nextInt()
→ 정수 읽기nextDouble()
→ 실수 읽기nextLine()
→ 한 줄 읽기next()
→ 공백 단위로 문자열 읽기 import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Name: " + name + ", Age: " + age);
scanner.close(); // 자원 해제
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileScannerExample {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("example.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close(); // 자원 해제
}
}
import java.util.Scanner;
public class StringScannerExample {
public static void main(String[] args) {
String input = "100 200 300";
Scanner scanner = new Scanner(input);
while (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println("Read number: " + number);
}
scanner.close(); // 자원 해제
}
}
메서드 | 설명 |
---|---|
next() | 공백 단위로 문자열을 읽음 |
nextLine() | 한 줄 전체를 읽음 |
nextInt() | 정수를 읽음 |
nextDouble() | 실수를 읽음 |
hasNext() | 다음 토큰이 있는지 확인 |
hasNextInt() | 다음 토큰이 정수인지 확인 |
useDelimiter(String) | 사용자 정의 구분자 설정 |
일반적으로 표준 입력(
System.in
) 대신 가짜 입력 스트림을 사용하는 방법을 활용합니다. 이로 인해 사용자가 콘솔에 입력하는 대신 테스트 코드에서 입력을 제어할 수 있습니다.
import java.util.Scanner;
public class InputHandler {
public int sumTwoNumbers() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
return num1 + num2;
}
}
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
public class InputHandlerTest {
@Test
public void testSumTwoNumbers() {
// 가짜 입력 설정 (예: 5와 10을 입력으로 제공)
String fakeInput = "5\n10\n";
System.setIn(new ByteArrayInputStream(fakeInput.getBytes()));
// 테스트 대상 메서드 실행
InputHandler inputHandler = new InputHandler();
int result = inputHandler.sumTwoNumbers();
// 결과 검증
assertEquals(15, result, "The sum of 5 and 10 should be 15");
}
}
ByteArrayInputStream
: 입력 데이터를 바이트 배열로 처리하여 System.in
으로 전달.System.setIn
: 테스트 중 System.in
을 가짜 입력 스트림으로 교체.assertEquals
: 예상 값과 실제 결과를 비교하여 검증.system.setIn
을 사용하면 전역적으로 영향을 미치므로, 테스트 후 복원하는 것이 좋습니다.InputStream originalIn = System.in;
try {
System.setIn(new ByteArrayInputStream(fakeInput.getBytes()));
// 테스트 실행
} finally {
System.setIn(originalIn);
}
Scanner
대신 입력을 매개변수로 전달하는 방식으로 리팩토링하는 것이 유지보수에 유리합니다.