Java 사용자 입력(스캐너)
자바 사용자 입력
클래스 는 Scanner
사용자 입력을 받는 데 사용되며 java.util
패키지에서 찾을 수 있습니다.
클래스 를 사용하려면 Scanner
클래스의 개체를 만들고 Scanner
클래스 설명서에 있는 사용 가능한 메서드를 사용합니다. 이 예에서는 nextLine()
문자열을 읽는 데 사용되는 메서드를 사용합니다.
예시
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
패키지가 무엇인지 모르는 경우 Java 패키지 자습서 를 읽으십시오 .
입력 유형
위의 예에서는 nextLine()
문자열을 읽는 데 사용되는 메서드를 사용했습니다. 다른 유형을 읽으려면 아래 표를 보십시오.
Method | Description |
---|---|
nextBoolean() |
Reads a boolean value from the user |
nextByte() |
Reads a byte value from the user |
nextDouble() |
Reads a double value from the user |
nextFloat() |
Reads a float value from the user |
nextInt() |
Reads a int value from the user |
nextLine() |
Reads a String value from the user |
nextLong() |
Reads a long value from the user |
nextShort() |
Reads a short value from the user |
아래 예에서는 다양한 방법을 사용하여 다양한 유형의 데이터를 읽습니다.
예시
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
참고: 잘못된 입력(예: 숫자 입력의 텍스트)을 입력하면 예외/오류 메시지(예: "InputMismatchException")가 표시됩니다.
예외 및 오류 처리 방법에 대한 자세한 내용은 예외 장 에서 읽을 수 있습니다 .