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

Java硬币计数代码调试后仍报错,求问题排查与修复协助

硬币转美元金额代码问题排查与修复

问题分析

  1. 核心计算逻辑错误:代码直接将硬币数量相加赋值给dollars,完全忽略每种硬币的面值差异(quarter=25美分、dime=10美分、nickel=5美分、penny=1美分),也未将总美分转换为美元(1美元=100美分),这是结果错误的根本原因。
  2. 输出格式混乱:美元符号与金额分开打印,且未按货币格式保留两位小数,显示效果不符合预期。
  3. 冗余代码:每次nextInt()后调用的stdio.nextLine()属于冗余操作,nextInt()会自动跳过输入中的空白字符(包括换行),这些调用无实际作用。

修复后的代码

import java.util.Scanner;

public class CountChangeWithScanner{
 
    public static void main(String[] args){
        int quarters; // 25美分硬币数量
        int dimes; // 10美分硬币数量
        int nickels; // 5美分硬币数量
        int pennies; // 1美分硬币数量

        Scanner stdio = new Scanner(System.in);
        double dollars; // 总美元金额

        // 读取用户输入
        System.out.print("Enter the number of quarters:  ");
        quarters = stdio.nextInt();

        System.out.print("Enter the number of dimes:  ");
        dimes = stdio.nextInt();

        System.out.print("Enter the number of nickels:  ");
        nickels = stdio.nextInt();

        System.out.print("Enter the number of pennies:  ");
        pennies = stdio.nextInt();

        // 计算总金额:先算总美分,再转换为美元
        int totalCents = quarters * 25 + dimes * 10 + nickels * 5 + pennies;
        dollars = totalCents / 100.0;

        // 格式化输出货币格式
        System.out.println("\nThe total in dollars is $" + String.format("%.2f", dollars) + "\n");
        
        stdio.close(); // 关闭Scanner资源
    }
}

修复说明

  • 新增totalCents变量计算总美分数值,再除以100.0转换为美元,确保计算逻辑正确。
  • 使用String.format("%.2f", dollars)将金额格式化为两位小数,符合货币显示规范,同时将美元符号与金额合并输出。
  • 移除冗余的stdio.nextLine()调用,关闭Scanner资源,优化代码结构。

内容的提问来源于stack exchange,提问作者Joshua D'Astoli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:50:28