อินพุตผู้ใช้ Java (สแกนเนอร์)
อินพุตผู้ใช้ Java
คลาสScanner
นี้ใช้เพื่อรับอินพุตของผู้ใช้ และพบได้ในjava.util
แพ็คเกจ
ในการใช้Scanner
คลาส ให้สร้างอ็อบเจ็กต์ของคลาสและใช้เมธอดใดๆ ที่มีอยู่ในScanner
เอกสารประกอบของคลาส ในตัวอย่างของเรา เราจะใช้nextLine()
method ซึ่งใช้ในการอ่าน Strings:
ตัวอย่าง
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 Packages Tutorialของเรา
ประเภทอินพุต
ในตัวอย่างข้างต้น เราใช้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")
คุณสามารถอ่านเพิ่มเติมเกี่ยวกับข้อยกเว้นและวิธีจัดการกับข้อผิดพลาดได้ใน บท ข้อยกเว้น