我希望就我从命令行读取用户输入的方式获得一些关于最佳实践和评论的意见。有没有推荐的方法来做到这一点,我是否正确使用了 try/catch 块?
我的示例在这里运行良好,但仍然想听听是否有“更清洁”的方式来做到这一点。非常感谢。例如,他是否需要在每个 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();
}
}
}
}