打印 ANSI 彩色消息后设置用户输入文本的颜色?

Setting color of user input text after printing an ANSI-colored message?

我是 运行 Netbeans 中的一个控制台应用程序,它提示用户输入,验证输入,如果输入验证失败并重新提示则打印错误消息。我已将错误消息设置为根据 this answer 以红色文本打印。完美运行,省一期

在第一个输入无效的情况下程序要求第二个输入后,用户在该错误消息后输入的颜色与错误消息的颜色相同。

例如,用户输入了无效的输入。他们在错误消息后再次输入。它应该以默认文本颜色打印(在我的版本中为黑色),但它打印为红色文本。

有没有一种方法可以让我停止在我的文本上应用 ANSI 颜色代码?某种结束标记?

代码:

public static void main(String[] args) 
{

    //Initialize keyboard input
    Scanner keyboard = new Scanner(System.in);

    //Print prompt to screen
    System.out.println("User input prompt goes here: ");

    //Store user input
    String inputGot = keyboard.nextLine();

    //Print a dummy error message
    System.out.println("\u001B[31m" + "This is an error of some sort.  "
            + "Please re-enter input: ");

    //Rerun input prompt (this would be looped in the real program)
    System.out.println("User input prompt goes here: ");

    //Store user input
    inputGot = keyboard.nextLine();
}

无论你想让红色文本在哪里停止,你都需要插入 ANSI 转义序列以关闭所有 ANSI 属性:"\u001b[0m".

查看此内容以了解您可能 want/need 的其他内容。 https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes