更新时间:2022-04-06 11:13:23 来源:极悦 浏览1180次
极悦小编告诉大家,在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天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习