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

Java Scanner输入异常:首个商品名称输入被跳过求助

Scanner商品录入程序输入跳过问题排查与解决

问题现象

使用Java Scanner编写商品信息录入程序,先通过scan.nextInt()获取购买商品数量,随后循环提示用户输入商品名称(调用scan.nextLine())及价格。实际运行时,首个商品名称的输入被直接跳过,直接进入价格输入环节,不符合预期流程。

预期流程:

Enter the 1st item name.
[用户输入商品名称]
How much did this item cost?
[用户输入价格]

实际流程:

Enter the 1st item name.
How much did this item cost?
[用户输入价格]

原因分析

scan.nextInt()方法仅读取输入流中的整数内容,用户输入数字后按下的**换行符(\n)**会残留在Scanner的输入缓冲区中。当首次执行scan.nextLine()时,它会直接读取缓冲区中残留的换行符,而不会等待用户输入,因此出现“跳过商品名称输入”的假象。

解决方法

在调用scan.nextInt()获取商品数量后,立即额外调用一次scan.nextLine(),清空缓冲区中残留的换行符,确保后续的scan.nextLine()能正常等待用户输入。

修正后代码

import java.util.Scanner;

public class ItemEntry {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int numOfItem = 0;
        String nameOfItem = "";
        double totalPrice = 0.0;

        System.out.println("How many items did the customer purchase?");
        numOfItem = scan.nextInt();
        // 清空nextInt()残留的换行符
        scan.nextLine();

        String numSuffix = "";
        for (int i = 1; i <= numOfItem; ++i) {
            String numStr = Integer.toString(i);
            if (numStr.length() > 1 && numStr.charAt(numStr.length() - 2) == '1') {
                numSuffix = "th";
            } else if (numStr.charAt(numStr.length() - 1) == '1') {
                numSuffix = "st";
            } else if (numStr.charAt(numStr.length() - 1) == '2') {
                numSuffix = "nd";
            } else if (numStr.charAt(numStr.length() - 1) == '3') {
                numSuffix = "rd";
            } else {
                numSuffix = "th";
            }
            System.out.println("Enter the " + i + numSuffix + " item name.");
            nameOfItem = scan.nextLine();

            System.out.println("How much did this item cost?");
            totalPrice += scan.nextDouble();
            // 清空nextDouble()残留的换行符,避免下一次循环的nextLine()受影响
            scan.nextLine();
        }

        scan.close();
        System.out.println("Total price: $" + totalPrice);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:15:23