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

Java Properties连续更新两个属性时首个Scanner输入被跳过如何解决

问题根源

你遇到的第一个输入步骤被跳过的问题,是Java Scanner 类的常见使用误区:
sc.nextInt() 方法只会读取输入的整数内容,不会读取用户输入完成后按下的换行符,这个换行符会残留在输入缓冲区中。后续第一次调用sc.nextLine()时,会直接读取到这个残留的换行符,返回空字符串,看起来就像直接跳过了第一个输入步骤,用户输入的内容会被第二个sc.nextLine()读取,赋值给GrapeFruitIzzie。

修复方案

方案1:消费掉nextInt残留的换行符

在choice = sc.nextInt();执行完成后,额外调用一次sc.nextLine()吃掉缓冲区残留的换行符,修改后代码如下:

System.out.println("Do you wish to update inventory? Type 2");
choice = sc.nextInt();
// 新增这行,清理缓冲区残留的换行符
sc.nextLine();

if (choice == 2){
  FileOutputStream out = new FileOutputStream("Stats.properties");

    System.out.println("Insert BlackBerry Amount");
    blackAmount = sc.nextLine();
    props.setProperty("BlackBerryIzzie", blackAmount);
 
    System.out.println("Insert GrapeFruit Amount");
    grapeAmount = sc.nextLine();
    props.setProperty("GrapeFruitIzzie", grapeAmount);

  props.store(out, null);
  out.close();  
}

方案2:统一使用nextLine读取所有输入

避免混用nextInt()和nextLine(),所有输入都用nextLine()读取,需要整数时自行做类型转换:

System.out.println("Do you wish to update inventory? Type 2");
// 读取字符串后转成整数
choice = Integer.parseInt(sc.nextLine());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:27:02