在Java中,是否有可能将用户的输入包含到异常消息中,同时还使用该值作为int
或double
?例如,他们应该输入一个数字(例如5),而不是像(5r)那样的胖手指。如何在异常消息Java中包含用户输入?
是否有可能发出类似“您输入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
它给出了错误cannot find symbol
。
以下是我想出的答案。我选择这个答案的原因是因为你的大部分答案产生了输出结果“你输入了0.0 ...”,因为答案必须是一个要在控制台中打印的字符串。此外,被用作许多其他地方的程序字符串已转换为类型的对象双人或整数:
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...
你有什么问题? – 2013-03-24 14:49:53
更新了o.p.显示错误 – Chris 2013-03-24 14:53:26
那么,你有很多答案可供选择。他们都基本上说同样的事情,所以你应该全部设置。 – 2013-03-24 14:53:56