在 Java 中,是否可以将用户的输入包含到异常消息中,同时将值用作 int
或 double
?例如,他们应该输入一个数字(例如 5),而不是像 (5r) 这样的粗手指。
是否可以显示类似“您输入了 5r,但应该输入数字。”的消息?
我尝试使用传统方式在 Java 中打印变量:
try {
System.out.println();
System.out.println("Value: ");
double value = sc.nextDouble();sc.nextLine();
exec.ds.push(value);
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
在本例中,我尝试获取异常消息中显示的 value
,其中 value 是用户的无效输入。
在值
处,它给出错误无法找到符号
。
下面是我想出的答案。我选择这个答案的原因是因为大多数答案都会产生输出“您输入了 0.0 ...”,因为答案首先必须是要在控制台中打印的字符串。此外,为了在程序中的其他位置用作数字,String 已转换为 Double 或 Integer 类型的对象:
String value = null; //declared variable outside of try/catch block and initialize.
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextLine(); //Accept String as most of you suggested
Double newVal = new Double(value); //convert the String to double for use elsewhere
exec.ds.push(newVal); //doulbe is getting used where it would be a 'number' instead of string
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number"); //the String valuse is received and printed as a String here, not a 'number'
} //now prints what the users inputs...
最佳答案
这不起作用,因为 value
不再位于 catch block 的范围内。相反,您可以在尝试之前声明它:
double value = 0;
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextDouble();sc.nextLine();
exec.ds.push(value);
} catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
但是,如果由于 double 中的语法错误而引发异常,这将无济于事。要处理此问题,您需要读取 String
,然后转换为 double
。
关于java - 如何在 Java 异常消息中包含用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15599837/