Scott Forsythe Scott Forsythe - 2 years ago 80
Java Question

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

I am running a console application in Netbeans that prompts a user input, validates the input, and prints an error message if the input failed validation and re-prompts. The error message I have set up to print in red text per this answer. It works perfectly, save one issue.

After the program asks for a second input given that the first input was invalid, user inputs following that error message are the same color as the error message.

For example, the user has entered an invalid input. They enter their input again after the error message. It should print in the default text color (black in my version), but it prints as red text instead.

Is there a way in which I am supposed to close out the application of the ANSI color code on my text? An end tag of sorts?


public static void main(String[] args)

//Initialize keyboard input
Scanner keyboard = new Scanner(;

//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();

Answer Source

Wherever you want the red text to stop, you need to insert the ANSI escape sequence to set all ANSI attributes off: "\u001b[0m".

See this for other things you might want/need.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download