Java 简明教程
Java - User Input
User Input in Java
要在 Java 中从用户获取输入,可以使用 Scanner 类。 Scanner 类是 java.util package 的内置类。
Java Scanner class 提供许多内置方法从用户获取不同类型的用户输入。
How to Use Scanner Class to Take User Input?
以下步骤介绍了如何在 Java 中将 Scanner 类用于用户输入:
Step 1: Import Scanner Class
首先,您需要导入 Scanner 类以使用其方法。要导入 Scanner 类,请使用以下导入语句:
import java.util.Scanner
Example of User Input in Java
在以下示例中,我们从用户读取两个整数,进行计算并打印它们的和:
// Importing the class
import java.util.Scanner;
public class AddTwoNumbers {
public static void main(String[] args) {
// Creating an object of Scanner class
Scanner sc = new Scanner(System.in);
// Reading two Integer numbers
// using nextInt() method
System.out.print("Enter the first number: ");
int num1 = sc.nextInt();
System.out.print("Enter the second number: ");
int num2 = sc.nextInt();
// Calculating the sum
int sum = num1 + num2;
// Printing the su
System.out.println("The sum of the two numbers is: " + sum);
}
}
Enter the first number: 10
Enter the second number: 20
The sum of the two numbers is: 30
Methods for Different Types of User Inputs
Scanner 类为不同用户输入提供了不同方法。要探索用于不同用户输入的所有方法,请查看下表:
Integer Input from the User
nextInt() method 用于从用户获取整数输入。
在以下示例中,我们以整数形式进行输入:
// Importing the class
import java.util.Scanner;
public class IntegerInput {
public static void main(String[] args) {
// Creating an object of Scanner class
Scanner sc = new Scanner(System.in);
// Reading an Integer Input
System.out.print("Input an integer value: ");
int int_num = sc.nextInt();
System.out.print("The input is : " + int_num);
}
}
Input an integer value: 101
The input is : 101
Float Input from the User
nextFloat() method 用于从用户获取浮点值输入。
在以下示例中,我们以浮点形式进行输入:
// Importing the class
import java.util.Scanner;
public class IntegerInput {
public static void main(String[] args) {
// Creating an object of Scanner class
Scanner sc = new Scanner(System.in);
// Reading a Float Input
System.out.print("Input a float value: ");
float float_num = sc.nextFloat();
System.out.print("The input is : " + float_num);
}
}
Input a float value: 12.345
The input is : 12.345
String Input from the User
nextLine() method 用于从用户获取浮点值输入。
在如下示例中,我们将一个字符串作为输入 −
// Importing the class
import java.util.Scanner;
public class IntegerInput {
public static void main(String[] args) {
// Creating an object of Scanner class
Scanner sc = new Scanner(System.in);
// Reading a String Input
System.out.print("Input a string value: ");
String str = sc.nextLine();
System.out.print("The input is : " + str);
}
}
Input a string value: Hello World
The input is : Hello World