问题描述
我正在尝试用Java编写交互式提示。 更具体地说,如下所示:
>>> load names;
>>> print names;
(即,它在每行上打印>>>
,然后用户输入命令。我编写了以下Java代码来完成此操作:
public static void main(String[] args) {
try {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String command;
System.out.print(">>> ");
while ((command = r.readLine()) != null) {
processCommand(command);
System.out.print(">>> ");
}
} catch (IOException e) {
System.out.println("Something went wrong.");
}
}
我的问题是:有没有更清洁的方法可以做到这一点?
我不喜欢在多个位置打印提示( >>>
)的想法,而且我认为应该有一种简单的方法,只需执行一次即可。
有什么清理建议吗?
1楼
怎么样
try {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String command = " ";
while (command != null) {
System.out.print(">>> ");
command = r.readLine();
processCommand(command);
}
} catch (IOException e) {
System.out.println("Something went wrong.");
}
2楼
您可以在processComand
的底部添加System.out.println(">>>");
try {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String command = " ";
do{
command = r.readLine();
processCommand(command);
}while (command != null)
} catch (IOException e) {
System.out.println("Something went wrong.");
}