连续输入命令

我的程序将以“ command parameter ”的forms读取用户键盘命令,其间有空格。 它一直执行单独的命令,直到下一个命令“ exit ”。 此外,如果用户搞砸了,程序应该显示错误但继续询问命令(我认为我没有完成的function)..

以下代码是实现此function的好方法吗? 它可以处理用户只需按下输入键w / oa命令,垃圾输入等? 如果有的话,我很想知道是否有更好的惯用方式来实现这一点。

 String command = ""; String parameter = ""; Scanner dataIn = new Scanner(System.in); while (!command.equals("exit")) { System.out.print(">> "); command = dataIn.next().trim(); parameter = dataIn.next().trim(); //should ^ these have error handling? if (command.equals("dothis")) { //do this w/ parameter.. } else if (command.equals("dothat")) { //do that w/ parameter.. } //else if... {} else { system.out.println("Command not valid."); } } System.out.println("Program exited by user."); 

注意:我接受了这个类没有一个关于exception处理的概念,因此非常感谢该领域的任何指针:)

这是实现输入循环的简单方法:

 Scanner sc = new Scanner(System.in); for (prompt(); sc.hasNextLine(); prompt()) { String line = sc.nextLine().replaceAll("\n", ""); // return pressed if (line.length == 0) continue; // split line into arguments String[] args = line.split(" "); // process arguments if (args.length == 1) { if (args[0].equalsIgnoreCase("exit")) System.exit(0); if (args[0].equalsIgnoreCase("dosomething")) // do something } else if (args.length == 2) { // do stuff with parameters } } 

假设prompt()在这里打印出提示。