更新時間:2022-04-06 11:13:23 來源:動力節點 瀏覽1485次
動力節點小編告訴大家,在Java中接受鍵盤輸入是使用 Scanner 對象完成的。
考慮以下陳述
Scanner console = new Scanner(System.in)
該語句聲明了一個名為 console 的引用變量。Scanner 對象與標準輸入設備 (System.in) 相關聯。
要從鍵盤獲取輸入,您可以調用 Scanner 類的方法。例如在以下語句中 Scanner 的 nextInt() 方法接受一個整數并返回變量 x :
int x = console.nextInt();
import java.util.Scanner; // Needed for Scanner class
/**
* This program demonstrates keyboard input.
*/
public class RectangleArea
{
public static void main(String[] args)
{
int length; // To hold rectangle's length.
int width; // To hold rectangle's width.
int area; // To hold rectangle's area
// Create a Scanner object to read input.
Scanner console = new Scanner(System.in);
// Get length from the user.
System.out.print("Enter length ");
length = console.nextInt();
// Get width from the user.
System.out.print("Enter width ");
width = console.nextInt();
// Calculate area.
area = length * width;
// Display area.
System.out.println("The area of rectangle is " + area);
}
}
輸出 :
輸入長度5
輸入寬度8
矩形的面積是40
例子 :
import java.util.Scanner;
/**
* This program demonstrates various Scanner methods.
*/
public class ReadEmployee
{
public static void main(String[] args)
{
String name; // To hold the employee's name
int age; // To hold the employee's age
char gender; // To hold the employee's gender
double salary; // To hold the employee's salary
// Create a Scanner object to read input.
Scanner console = new Scanner(System.in);
// Get the employee's name
System.out.print("Enter name: ");
name = console.nextLine();
// Get the employee's age
System.out.print("Enter age: ");
age = console.nextInt();
// Get the employee's gender
System.out.print("Enter gender: ");
gender = console.next().charAt(0);
// Get the employee's salary
System.out.print("Enter salary: ");
salary = console.nextDouble();
// Display the information
System.out.println("Name: " + name + " Age: " + age + " Gender: "
+ gender + " Salary: " + salary);
}
}
輸出 :
輸入姓名:Alex Joseph
輸入年齡:24
輸入性別:M
輸入薪水:8000
姓名:Alex Joseph 年齡:24 性別:M 薪水:8000.0
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習