我有一个非常简单的问题(我开始使用Java),但出于某种原因,我找不到合适的答案。我正在制作一个程序,用户必须做出选择和输入。但我需要检查有效输入,如果他输入char
而不是int
,我需要给他一个错误信息。
代码是:
Scanner n = new Scanner (System.in);
System.out.print("...");
sp = n.nextInt();
if ( sp != 1 )
{
if ( sp == 2 )
{
System.out.println("...");
}
}
else
System.out.println("...");
**//and here the error message shoub be,**
**//in case the user inputs something different than a int**
答案 0 :(得分:0)
您是否尝试过使用Java的try .... catch语句。我建议你像这样包装你的代码:
try{
//put your code here
} catch(e){
System.out.println(e.message)
}
您可以研究有关处理IO错误的更多信息,并在代码中加入一些额外的保护。希望这有帮助!
答案 1 :(得分:0)
你可能需要像这样添加try catch ...它应该工作正常...如果用户现在输入一个字符串,它将抛出异常并且catch块将起作用
Scanner n = new Scanner (System.in);
System.out.print("...");
try{
sp = n.nextInt();
} catch(Exception e){
//Display your message here
}
if ( sp != 1 ) {
if ( sp == 2 ) {
System.out.println("...");
}
} else
System.out.println("...");