【发布时间】:2015-04-27 13:08:57
【问题描述】:
我有这个简单的代码,就像一个小命令提示符一样工作。要求用户输入命令,并根据他输入的内容显示一条消息。我只想让它循环,以便用户被要求一次又一次地输入命令,直到他键入“退出”。我怎么做? 代码如下:
public static void main(String[] args) {
Scanner command = new Scanner(System.in);
System.out.println("Enter command: ");
String text = command.nextLine();
switch(text){
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped.");
break;
case "exit":
System.out.println("Application Closed");
break;
default:
System.out.println("Command not recognized!");
break;
}
command.close();
}
谢谢
【问题讨论】:
-
while ( 不满足条件 ){ /* 你的代码 */ 重置值来测试 }
-
尝试使用链式 if-else 并使用 text.equals("xxxxxx") 作为条件。
-
@farukdgn:他为什么要那样做?
-
@Stultuske *.com/a/513839/3025112
-
@farukdgn:您正在测试错误的值。 "xxxxxxxx" 和 "exit" 永远不会相等。但是,我指的是您的 if-else 建议。
标签: java while-loop