当前位置: 代码迷 >> java >> 清理命令行提示符(Java)的打印
  详细解决方案

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

热度:45   发布时间:2023-07-17 20:08:51.0

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

我的问题是:有没有更清洁的方法可以做到这一点? 我不喜欢在多个位置打印提示( >>> )的想法,而且我认为应该有一种简单的方法,只需执行一次即可。

有什么清理建议吗?

怎么样

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

您可以在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.");
 }
  相关解决方案