【问题标题】:Why won't ">> " print at the end of my printf statement?为什么在我的 printf 语句末尾不打印“>>”?
【发布时间】:2014-02-16 00:00:12
【问题描述】:

我正在尝试使用 Jansi Java 库在 CMD/控制台中使用颜色,但遇到了一个小问题。当我使用 Jansi 库并尝试使用 print f 语句时

System.out.printf("Hello young lad! What is thy " + RED + "name " + WHITE + "you were given at birth?\n>> ");

“>>”最后不打印。相反,扫描仪被调用并询问我的输入。为什么会发生这种情况,我有什么办法可以让“>>”和 Scanner 输入出现在一行上?

import java.util.Scanner;

import org.fusesource.jansi.AnsiConsole;


public class Test {
    public static void main(String[] args) {
        AnsiConsole.systemInstall();

        String name;
        Scanner scanner = new Scanner(System.in);

        String BLACK = "\u001B[0;30m";
        String RED = "\u001B[0;31m";
        String GREEN = "\u001B[0;32m";
        String YELLOW = "\u001B[0;33m";
        String BLUE = "\u001B[0;34m";
        String MAGENTA = "\u001B[0;35m";
        String CYAN = "\u001B[0;36m";
        String WHITE = "\u001B[0;37m";

        System.out.printf("Hello young lad! What is thy " + RED + "name " + WHITE + "you were given at birth?\n>> ");
        name = scanner.nextLine();
    }
}

【问题讨论】:

  • 尝试在拨打nextLine()之前添加System.out.flush();
  • 忽略 AnsiConsole 的东西,它对我有用。看起来你的系统对我来说可能是行缓冲的。
  • 您正在呼叫printf,但没有使用它的任何功能。如果您不知道printf 的含义,最好使用print

标签: java input cmd textcolor text-coloring


【解决方案1】:

注释掉 AnsiConsole 之后,这段代码运行良好。

这是我打印出来的。

Hello young lad! What is thy [0;31mname [0;37myou were given at birth?
>> John

【讨论】:

  • 如果问题与 Jansi 的控制台有关怎么办?
  • @zakinster 那么它会与 jAnsi 的 ANSI 控制台有关。
最近更新 更多