You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何实现输入操作与后续输出内容在同一行显示?

问题

在Java中有没有办法确保用户输入值后,后续输出内容直接紧邻输入提示显示在同一行,而非换行?也就是实现输入与输出在同一行展示的效果?

预期输出:

Factorial of 5: 120

实际输出:

Factorial of 5
: 120

参考代码:

public class Main {

  public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    int total = 1;
    int i;
    System.out.print("Factorial of ");
    int input = s.nextInt();
    for (i = 1; i <= input; i++) {
      total *= i;
    }
    System.out.print(": " + total);
  }
}
原因分析

出现换行是因为用户输入完按下回车键后,控制台会自动换行显示输入内容,而Scanner.nextInt()仅读取数字部分,不会处理输入缓冲区里的换行符,后续输出只能从新行开始。

解决方案

方案一:利用Console类+ANSI转义序列(支持ANSI的终端可用)

这种方法通过调整光标位置,将后续输出移至输入内容的同一行末尾,实现实时追加的效果。

public class Main {
    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.err.println("当前环境不支持控制台操作,请在终端运行程序");
            return;
        }

        int total = 1;
        String inputStr = console.readLine("Factorial of ");
        int input = Integer.parseInt(inputStr);

        // 计算阶乘
        for (int i = 1; i <= input; i++) {
            total *= i;
        }

        // ANSI转义:光标移回上一行
        System.out.print("\033[1A");
        // 光标右移至输入内容末尾
        int cursorPos = "Factorial of ".length() + inputStr.length();
        System.out.print("\033[" + cursorPos + "C");

        // 输出结果
        System.out.print(": " + total);
        System.out.println();
    }
}

注:ANSI转义序列在Linux/macOS终端、Windows 10+的PowerShell(需开启支持)中可用,旧版CMD不支持。

方案二:一次性输出完整内容(全环境兼容)

如果控制台不支持ANSI转义,可以先读取输入,再一次性输出预期格式的内容,最终也能得到同一行的结果。

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int total = 1;

        System.out.print("请输入一个数字:");
        int input = s.nextInt();

        // 计算阶乘
        for (int i = 1; i <= input; i++) {
            total *= i;
        }

        // 一次性输出完整行
        System.out.println("Factorial of " + input + ": " + total);
    }
}

内容的提问来源于stack exchange,提问作者First name Last name

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 01:35:27