【发布时间】:2013-03-24 14:46:03
【问题描述】:
是否可以在 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 是用户的无效输入。
在value 它给出了错误cannot find symbol。
以下是我想出的答案。我选择这个答案的原因是因为您的大多数答案都产生了输出“您输入了 0.0 ...”,因为答案必须首先是要在控制台中打印的字符串。此外,要在程序的其他地方用作数字,String 已强制转换为 Double 或 Integer 类型的 Object:
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...
【问题讨论】:
-
你遇到了什么问题?
-
更新了 o.p.显示错误
-
嗯,你有很多答案可供选择。他们基本上都说同样的话,所以你应该都准备好了。
标签: java exception-handling io console-application