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

Java Scanner调用print()后先要求输入才打印提示该如何解决

问题根因

Java的System.out标准输出默认采用行缓冲机制,仅当遇到换行符、缓冲区被填满、程序主动刷新、进程结束时,才会将缓冲区中的内容真正输出到终端。使用无换行的print()输出提示文本时,内容会暂存在缓冲区中不会立刻打印,直到后续第一次调用println()输出时触发换行,才会把之前攒的所有缓冲内容一次性输出,因此出现了需要先输入两次值才会看到提示的问题。

最小改动修复方案

只需要在每句print()输出提示后,手动调用flush()方法刷新输出缓冲区即可,完全满足输入内容与提示在同一行的要求,仅新增2行代码,同时修正原代码中字符串缺闭合双引号的语法问题:

import java.util.Scanner;
public class temperature {

    public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);

    System.out.print("Enter today's temperature: ");
    System.out.flush();
    int today = keyboard.nextInt();

    System.out.print("Enter tomorrow's temperature: ");
    System.out.flush();
    int tomorrow = keyboard.nextInt();

    System.out.println("Today is " + today + " degrees.");
    System.out.println("Tomorrow is " + tomorrow + " degrees.");
  }
}

修改后运行即可符合预期输出效果。

内容的提问来源于stack exchange,提问作者HelixAu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:57:04