2013-03-24 60 views
0

在Java中,是否有可能将用户的输入包含到异常消息中,同时还使用该值作为intdouble?例如,他们应该输入一个数字(例如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... 
+0

你有什么问题? – 2013-03-24 14:49:53

+0

更新了o.p.显示错误 – Chris 2013-03-24 14:53:26

+1

那么,你有很多答案可供选择。他们都基本上说同样的事情,所以你应该全部设置。 – 2013-03-24 14:53:56

回答

1

这不起作用,因为value不再位于catch块的范围内。相反,你可以在try之前声明它:

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");        
} 

如果异常是因为在双语法错误抛出然而,这将于事无补。要处理此问题,您需要阅读String,然后转换为double

1

值它给出了错误无法找到象征。

您已声明本地块中的值。你正试图在块外访问它。

是否有可能有一个消息说类似“您输入5R,但应该已经进入了一个号码。

更好的选择是使用标志变量和循环,直到用户输入正确的数字。

boolean flag = true; 
double value = 0; 
while(flag) 
{ 
    try { 
     System.out.println(); 
     System.out.println("Value: "); 
     value = sc.nextDouble(); 
     exec.ds.push(value); 
     flag = false; 
    } 
    catch (Exception e1) { 
     System.out.println(e1+ "You entered: " + value + ": You must enter a number");        
    } 
} 
1

获取用户输入:

String input = ''; 

try{ 

    Console console = System.console(); 
    input = console.readLine("Enter input:"); 
} 

...然后在你赶上你可以做的:

catch (Exception e1) { 
    System.out.println(e1+ "You entered: " + input + ": You must enter a number");        
    } 

除了上述,我不明白是什么问题。你可以谷歌如何获得用户输入的Java,然后只需要输入,将其放入一个变量,并在出错时打印出来。

1

在这种情况下 - 不,因为调用sc.nextLine()会导致异常被抛出,所以没有值写入变量value

而且,value在这种情况下是局部变量,并且不可用于其他代码块。

0

按照documentationnextDouble()

扫描输入作为双的下一个标记。如果下一个标记不能转换为有效的double值,则此方法将抛出InputMismatchException

因此,如果输入无法翻译成双精度型,则抛出异常。如果您想在异常消息中提供输入的字符串,我建议您将该行作为字符串读取,并尝试将其解析为double,如果失败,可以将读取行包含在异常消息中。