在Java中使用boolean打印无效命令
我正在尝试构建自己的命令行界面 最令人困惑的部分是根据用户输入打印出无效的命令 我尝试使用布尔函数检查每个命令的有效性 我希望我的程序继续运行,即使我的命令无效 如何在退出在Java中使用boolean打印无效命令,java,boolean,Java,Boolean,我正在尝试构建自己的命令行界面 最令人困惑的部分是根据用户输入打印出无效的命令 我尝试使用布尔函数检查每个命令的有效性 我希望我的程序继续运行,即使我的命令无效 如何在退出循环后再次进入循环 String command; BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); boolean R = true; while (R==true) { System.out.print("
循环后再次进入循环
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();
String命令;
BufferedReader控制台=新的BufferedReader(新的InputStreamReader(System.in));
布尔R=真;
while(R==true){
系统输出打印(“命令:”);
command=console.readLine();
R=假;
ArrayList commandParams=新的ArrayList();
String[]commandSplit=command.split(“”);
如果(commandSplit.length>1){
for(int i=1;i
在循环中移动无效命令的代码,即
while (R==true) {
System.out.print("command: ");
command = console.readLine();
R=false;
...
//Exit the console when "exit" is entered.
if (commandSplit[0].equals("exit")) {
System.exit(0);
R=true;
}
if(R==false){
System.out.println("invalid command");
R=true;
}
}
}
你可以这样做。您甚至不需要布尔变量
while (true) {
String command = console.readLine();
if (command.equals("date")) {
//print date
continue;
}
if (command.equals("time")) {
//print time
continue;
}
if (command.equals("exit")) {
break;
}
System.out.println("invalid command");
command = console.readLine();
}
具体的答案是:你不能回到它
但是想想看:您真的需要每次都将布尔变量设置为false吗?不,只有当你想终止程序时才需要
您可以使用很多if-else语句,但由于JDK 7,我们最终能够比较switch case结构中的字符串,这将非常适合您的需要:
boolean loop = true;
while ( loop )
{
// Your read and parse functions go here...
switch ( commandSplit[ 0 ] )
{
case "exit":
loop = false;
break;
case "time":
// dummy method
printTime();
break;
// default will be executed if none of the above cases is met.
default:
System.out.println( "Invalid / Unknown command." );
break;
}
}
// shutdown logic goes here (if needed).
这样做可以方便地扩展程序的功能,因为如果要执行新命令,可以方便地添加新案例。当用户打算从控制台出来时,可以进入exit。但是由于布尔标志(R)被设置,程序永远不会正确终止?@User27854他调用System.exit(0)
如果命令等于“exit”,那么程序将终止。我错过了,抱歉:)你就快到了,你所要做的就是删除R=false;并且仅当用户决定结束会话时,才将此值设置为false。一个问题是为什么要使用command=console.readLine();节目结束时,我错过了这个。