我可以使用什么代码来防止运行时错误?

时间:2014-01-17 02:02:46

标签: java

我正在编写一个程序,其中我提示用户输入介于1和44之间的数字。但是,我可以添加哪些代码以防止他们输入一个带有用户友好消息且没有运行时错误的数字?

2 个答案:

答案 0 :(得分:1)

试试这个:

try {

   // Your code goes here ...   

} catch(RuntimeException e) {
  // Handle RuntimeException here
  //log.warn("Something bad happened Harry... Hopefully, we can recover!", e);
} 

答案 1 :(得分:1)

if(number < 1 || number > 44) {
    //prompt again
}

修改

正如评论中所述,使用while循环会强制用户继续操作,直到他们输入有效数字。

while (number < 1 || number > 44) {
    //prompt again
}