清理命令行提示符的打印 (Java)

Cleaning up printing of command-line prompt (Java)

我正在尝试在 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.");
    }
}

我的问题:有没有更简洁的方法来做到这一点?我不喜欢必须在多个地方打印提示 (>>>) 的想法,我觉得应该有一种简单的方法只需要执行一次。

有什么清理建议吗?

您可以添加到 processComandSystem.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.");
 }

这样做怎么样

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.");
 }