以正确的方式从java中的命令行读取用户输入
问题描述:
我希望从我从命令行读取用户输入的方式上获得一些有关最佳实践和评论的意见。有没有推荐的方法来做到这一点,我正确地使用try/catch块吗?以正确的方式从java中的命令行读取用户输入
我的例子在这里工作正常,但仍然希望听到如果有一个'干净'的方式来做到这一点。非常感谢。例如,他是否需要在每个catch块中返回语句? 或者,我应该把我的逻辑(条件)放在try块内吗?
公共类客户{
public static void main(String[] args) {
begin();
}
private static void begin(){
Machine aMachine = new Machine();
String select=null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(aMachine.stillRunning()){
try {
select = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your selection");
return;
}catch(Exception ex){
System.out.println("Error trying to evaluate your input");
return;
}
if (Pattern.matches("[rqRQ1-6]", select)) {
aMachine.getCommand(select.toUpperCase()).execute(aMachine);
}
/*
* Ignore blank input lines and simply
* redisplay options
*/
else if(select.trim().isEmpty()){
aMachine.getStatus();
}
else {
System.out.println(aMachine.badCommand()+select);
aMachine.getStatus();
}
}
}
}
答
我通常perfer要使用扫描仪类从输入线来读取。使用扫描仪类,您可以请求特定类型(double,int,...,string)。这也将为你做验证测试。
我不会推荐用你做的方式编写输入解析。捕获泛型异常将捕获任何内容,从MemoryError等。坚持特定的例外,并从那里处理它们。如果输入与预期类型不匹配,则扫描程序将通过InvalidInputException(或影响的内容)。
因此,扫描器不需要使用try/catch块和异常处理? – denchr 2009-11-15 14:54:31
它不需要它,但它会将它们投入不良输入。 – monksy 2009-11-15 16:04:36