在 Java 中获取用户输入通常涉及到使用 java.util.Scanner 类。下面是如何使用 Scanner 类来获取不同类型的用户输入的基本步骤和示例。
步骤
-
导入 Scanner 类 使用 import java.util.Scanner; 导入 Scanner 类。
-
创建 Scanner 对象 使用 Scanner() 构造函数创建 Scanner 类的一个实例。
Scanner scanner = new Scanner(System.in);
-
获取用户输入 Scanner 类提供了多种方法来读取不同类型的输入数据。
示例
下面是一个简单的示例,演示如何读取两个整数并计算它们的和:
import java.util.Scanner;
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
int sum = num1 + num2;
System.out.println("The sum of the two numbers is: " + sum);
scanner.close();
}
}
不同类型的用户输入
Scanner 类提供了多种方法来处理不同类型的用户输入:
| 序号 |
方法 & 描述 |
| 1 |
String next() |
| 2 |
BigDecimal nextBigDecimal() |
| 3 |
BigInteger nextBigInteger() |
| 4 |
boolean nextBoolean() |
| 5 |
byte nextByte() |
| 6 |
double nextDouble() |
| 7 |
float nextFloat() |
| 8 |
int nextInt() |
| 9 |
String nextLine() |
| 10 |
long nextLong() |
| 11 |
short nextShort() |
示例:不同类型的输入
整型输入
import java.util.Scanner;
public class IntegerInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input an integer value: ");
int intNum = scanner.nextInt();
System.out.println("The input is : " + intNum);
scanner.close();
}
}
浮点型输入
import java.util.Scanner;
public class FloatInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a float value: ");
float floatNum = scanner.nextFloat();
System.out.println("The input is : " + floatNum);
scanner.close();
}
}
字符串输入
import java.util.Scanner;
public class StringInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a string value: ");
String str = scanner.nextLine();
System.out.println("The input is : " + str);
scanner.close();
}
}
注意,在使用完 Scanner 对象之后,最好调用 scanner.close() 来关闭它,以避免潜在的资源泄露问题。