我正在 try catch 一个InputMismatchException,扫描仪需要一个 double 值,如果输入等于“c”或“q”,我想在catch block 中运行一些特定的代码。我想知道是否有办法在引发异常后获取用户输入的值。例如,如果代码调用 double 并且用户输入字母“c”,我希望能够知 Prop 体输入了“c”,并且如果为真则执行某些操作。这是我尝试编写的代码,其中“getValue()”是一个虚构的方法名称,用于描述我想要完成的任务:
double value = 0.0;
try{
System.out.print("\nEnter a number: ");
value = input.nextDouble();
}
catch(InputMismatchException notADouble){
if(notADouble.getValue().equalsIgnoreCase("c")){
//run the specific code for "c"
}
else if(notADouble.getValue().equalsIgnoreCase("q")){
//run the specific code for "q"
}
else{
System.out.print("\nInvalid Input");
}
}
预先感谢您的输入:)
最佳答案
在 Scanner 尝试将输入转换为数字之前,使用 Scanner.hasNextDouble()
验证输入。像这样的东西应该有效:
double value = 0.0;
Scanner input = new Scanner(System.in);
System.out.print("\nEnter a number: ");
while(input.hasNext())
{
while(input.hasNextDouble())
{
value = input.nextDouble();
}
String next = input.next();
if("c".equals(next))
{
//do something
}
else if("q".equals(next))
{
//do something
}
else
{
System.out.print("\nInvalid Input");
//return or throw exception
}
}
关于Java:获取引发异常的用户输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19468655/