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

Java硬币找零计算程序编译错误排查求助

硬币金额计算程序错误排查与修正

编译错误排查

你遇到的java.lang.Error: Unresolved compilation problem错误,核心原因是Java文件名与公共类名不匹配:

  • 代码中公共类名为CountChangeWithScanner,但运行时的文件名是Change counter.java
  • Java要求公共类的文件名必须和类名完全一致,且文件名不能包含空格
  • 解决方法:将文件名改为CountChangeWithScanner.java

逻辑错误修正

即使编译通过,原代码的金额计算逻辑也存在精度丢失问题:

  • 原公式dollars = quarters * 25 + dimes * 10 + nickels * 5 + pennies / 100属于整数运算:
    • pennies / 100是整数除法,比如输入50便士会得到0,而非0.5美元
    • 前面的quarters*25等计算的是总分数,但直接赋值给double变量会被当成整数(比如4个25美分硬币会被算成100.0美元,而非1.0美元)
  • 正确计算方式:先计算总分数,再除以100.0转成美元(或直接用硬币的美元面值计算):
    // 方式1:先算总分数再转美元
    dollars = (quarters * 25 + dimes * 10 + nickels * 5 + pennies) / 100.0;
    // 方式2:直接用美元面值计算
    dollars = quarters * 0.25 + dimes * 0.1 + nickels * 0.05 + pennies * 0.01;
    

可优化细节

  • 无需在每次stdio.nextInt()后调用stdio.nextLine(),nextInt()仅读取整数,后续换行符不会影响下一次输入
  • 可以格式化输出,让美元金额显示为两位小数,更符合货币展示习惯:
    System.out.printf("The total in dollars is $%.2f%n", dollars);
    

完整修正代码

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();

        // 正确计算美元总额
        dollars = (quarters * 25 + dimes * 10 + nickels * 5 + pennies) / 100.0;

        // 格式化输出结果
        System.out.println();
        System.out.printf("The total in dollars is $%.2f%n", dollars);
        System.out.println();
        
        stdio.close();
    }
}

内容的提问来源于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:29