【发布时间】:2018-05-09 10:47:08
【问题描述】:
我正在尝试构建自己的命令行界面。
最令人困惑的部分是根据用户输入打印出无效的命令。
我尝试使用布尔函数来检查每个命令的有效性。
即使我的命令无效,我也希望我的程序继续运行。
退出while循环后如何再次进入?
String command;
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
boolean R = true;
while (R==true) {
System.out.print("Command: ");
command = console.readLine();
R = false;
ArrayList commandParams = new ArrayList();
String[] commandSplit = command.split(" ");
if (commandSplit.length > 1) {
for (int i = 1; i < commandSplit.length; i++) {
commandParams.add(commandSplit[i]);
}
}
if (commandSplit[0].equals("time")) {
Date time = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss ");
System.out.println(sdf.format(time));
R = true;
}
// Print today's date.
if (commandSplit[0].equals("date")) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(" YYYY/MM/DD");
System.out.println(sdf.format(date));
R = true;
}
// Exit the console when "exit" is entered.
if (commandSplit[0].equals("exit")) {
System.exit(0);
R = true;
}
}
System.out.println("Invalid command");
System.out.print("Command: ");
command = console.readLine();
【问题讨论】:
-
你快到了,你所要做的就是删除 R=false;并仅在用户决定结束会话时将此值设置为 false。你的一个问题是为什么你有 command = console.readLine();在程序结束时,我错过了这个。