You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
108 lines
3.0 KiB
108 lines
3.0 KiB
package com.studentmanagement.util;
|
|
|
|
import java.util.Scanner;
|
|
|
|
/**
|
|
* 输入工具类,提供安全的用户输入处理
|
|
*/
|
|
public class InputUtil {
|
|
private static final Scanner scanner = new Scanner(System.in);
|
|
|
|
/**
|
|
* 获取用户输入的整数
|
|
* @param prompt 提示信息
|
|
* @return 输入的整数
|
|
*/
|
|
public static int getIntInput(String prompt) {
|
|
while (true) {
|
|
System.out.print(prompt);
|
|
try {
|
|
return Integer.parseInt(scanner.nextLine());
|
|
} catch (NumberFormatException e) {
|
|
System.err.println("请输入有效的整数!");
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取用户输入的整数,带范围检查
|
|
* @param prompt 提示信息
|
|
* @param min 最小值
|
|
* @param max 最大值
|
|
* @return 输入的整数
|
|
*/
|
|
public static int getIntInput(String prompt, int min, int max) {
|
|
while (true) {
|
|
int value = getIntInput(prompt);
|
|
if (value >= min && value <= max) {
|
|
return value;
|
|
}
|
|
System.err.println("请输入" + min + "到" + max + "之间的整数!");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取用户输入的字符串
|
|
* @param prompt 提示信息
|
|
* @return 输入的字符串
|
|
*/
|
|
public static String getStringInput(String prompt) {
|
|
System.out.print(prompt);
|
|
return scanner.nextLine().trim();
|
|
}
|
|
|
|
/**
|
|
* 获取用户输入的非空字符串
|
|
* @param prompt 提示信息
|
|
* @return 输入的非空字符串
|
|
*/
|
|
public static String getNonEmptyStringInput(String prompt) {
|
|
while (true) {
|
|
String input = getStringInput(prompt);
|
|
if (!input.isEmpty()) {
|
|
return input;
|
|
}
|
|
System.err.println("输入不能为空!");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取用户输入的浮点数
|
|
* @param prompt 提示信息
|
|
* @return 输入的浮点数
|
|
*/
|
|
public static double getDoubleInput(String prompt) {
|
|
while (true) {
|
|
System.out.print(prompt);
|
|
try {
|
|
return Double.parseDouble(scanner.nextLine());
|
|
} catch (NumberFormatException e) {
|
|
System.err.println("请输入有效的数字!");
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取用户输入的浮点数,带范围检查
|
|
* @param prompt 提示信息
|
|
* @param min 最小值
|
|
* @param max 最大值
|
|
* @return 输入的浮点数
|
|
*/
|
|
public static double getDoubleInput(String prompt, double min, double max) {
|
|
while (true) {
|
|
double value = getDoubleInput(prompt);
|
|
if (value >= min && value <= max) {
|
|
return value;
|
|
}
|
|
System.err.println("请输入" + min + "到" + max + "之间的数字!");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 关闭扫描器
|
|
*/
|
|
public static void close() {
|
|
scanner.close();
|
|
}
|
|
} |