Java tut 33 : Java User Input (Scanner) – Giá trị người dùng nhập vào 0 (0)

Java tut 33 : Java User Input (Scanner) – Giá trị người dùng nhập vào 0 (0)

Java tut 33 : Java User Input (Scanner) – Giá trị người dùng nhập vào 0 (0)

Learn more »

https://www.w3schools.com/java/java_user_input.asp

Java User Input

Các Scannerlớp học được sử dụng để có được đầu vào người sử dụng, và nó được tìm thấy trong các java.utilgói.

Để sử dụng Scannerlớp, hãy tạo một đối tượng của lớp và sử dụng bất kỳ phương thức nào có sẵn trong Scannertài liệu lớp. Trong ví dụ của chúng tôi, chúng tôi sẽ sử dụng nextLine()phương thức, được sử dụng để đọc các Chuỗi:

Thí dụ

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   } }  

Chạy ví dụ »

Nếu bạn không biết gói là gì, hãy đọc Hướng dẫn về gói Java của chúng tôi .


Các loại đầu vào

Trong ví dụ trên, chúng tôi đã sử dụng nextLine()phương thức, được sử dụng để đọc các Chuỗi. Để đọc các loại khác, hãy xem bảng dưới đây:

MethodDescription
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

Trong ví dụ dưới đây, chúng tôi sử dụng các phương pháp khác nhau để đọc các loại dữ liệu:

Thí dụ

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);   } }  

Chạy ví dụ »

Lưu ý: Nếu bạn nhập sai đầu vào (ví dụ: văn bản trong đầu vào số), bạn sẽ nhận được thông báo lỗi / ngoại lệ (như “InputMismatchException”).

Bạn có thể đọc thêm về các ngoại lệ và cách xử lý lỗi trong chương Ngoại lệ .


Lượt xem : 222

Integrations
Users

Share Profile

Anyone at KeenThemes can view
Anyone with link can edit

Give Award

Anyone at KeenThemes can view
Anyone with link can edit

Report User

Let us know why you’re reporing this person
Don't worry, your report is completely anonymous; the person you're
reporting will not be informed that you've submitted it