开发者

Design: How to handle illegal console inputs with Scanner?

From a design standpoint, what is the best way to handle illegal input from a user that is defined by the programmer.

Ex: I ask for a user to input quantity, but he inputs "fewfiejfjw".

Should I make a custom exception? Is there a commonly accepted exception to be thrown in this case? Or should I just say

if(!in.next().matches("\b\d+\b"){
System.out.print("Try again");
//..code to repeat method go开发者_如何学编程es here
}

Thanks for any help.


Scanner has a class of methods for checking whether the next token is a valid integer etc. For an example, see hasNextInt(). Call this before calling nextInt() etc.

What is the best way to handle invalid input really depends on your application. I guess it's not unreasonable to ask the user to enter the value again (of course, having skipped past the invalid token so that you don't create an infinite loop).


I don't think you should throw an exception. You should handle the input and show an error and ask the user to try again. No reason to stop the application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜