我正在创建一个类来处理用户输入。这样,在其他项目中我就可以从类中调用方法,而不必担心在每个新项目中创建扫描仪。
类中将有一个单独的方法来处理不同的变量类型(float、int、String 等)。我从 float 类型开始:
import java.util.Scanner;
public class Input {
public static float floatInput() {
Scanner in1 = new Scanner(System.in);
float in;
if (in1.hasNextFloat()) {
in = in1.nextFloat();
return in;
} else {
System.out.print("Incorrect input type, try again");
floatInput();
return 0;
}
}
这个方法工作得很好,除了它必须在 else 部分返回一个 float 。在本例中,它是零,因此当输入计算器(例如)时,零会导致任何输出等于零。
有没有办法返回“空”浮点值来解决这个问题?
对于一般情况下处理不正确的扫描仪输入,有人有更好的建议吗?
谢谢。
最佳答案
您可以将输入作为字符串
读取并检查它是否是浮点值,否则循环直到它是浮点值或用户感到厌倦:
public static float floatInput() {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a float:");
for(;;){
try{
return Float.parseFloat(scanner.next());
} catch(NumberFormatException e){
System.out.println("Incorrect input type, try again:");
}
}
}
关于java - 如何处理扫描仪中不正确的用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50858957/