首页 > 解决方案 > 更改字符串的输入颜色

问题描述

我想将输入字符串的颜色更改为绿色。用户键入时,它将为绿色。我不想先输入字符串然后更改颜色。谁能告诉如何做到这一点?

System.out.print("Please enter a sentence: ");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();   // I want to change the color to green when user typing the string

输出:

标签: java

解决方案


您可以使用ANSI 转义以与更改输出颜色相同的方式更改输入颜色。这是一篇专门针对 Java 的帖子。

\u001b[0m诀窍是在读取用户输入之前不要将其重置为正常 ( )。例如:

System.out.print("Please enter a sentence: \u001b[92m"); // Note the \u001b[92m after the prompt
Scanner s = new Scanner(System.in);
String name = s.nextLine();
System.out.println("\u001b[0mOther output"); // note the reset \u001b[0m

这可能不适用于您的 IDE 控制台,因为某些 IDE 将单独的颜色(您可以在设置中设置)应用于所有控制台输入。所以你应该在你的计算机命令行中运行它(例如cmd,Terminal.app 等)。

在此处输入图像描述


推荐阅读