Java硬币计数代码调试后仍报错,求问题排查与修复协助
硬币转美元金额代码问题排查与修复
问题分析
- 核心计算逻辑错误:代码直接将硬币数量相加赋值给
dollars,完全忽略每种硬币的面值差异(quarter=25美分、dime=10美分、nickel=5美分、penny=1美分),也未将总美分转换为美元(1美元=100美分),这是结果错误的根本原因。 - 输出格式混乱:美元符号与金额分开打印,且未按货币格式保留两位小数,显示效果不符合预期。
- 冗余代码:每次
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
相关产品推荐
相关产品推荐

