Java汇率计算程序输出异常:预期110.5却得到1.0求排查
汇率计算程序问题排查与修复
关键错误点
参数顺序完全颠倒:
calculateMaxAmount方法的参数定义是currentCurrency(当前持有货币)在前、targetCurrency(目标货币)在后,但main方法调用时把顺序搞反了。这导致程序一开始就判定当前货币和目标货币相同,直接返回初始金额1.0,这是输出1.0的根本原因。输入解析逻辑错误:
- 用户输入的每个汇率对包含三个字段(如
USD,CAD,1.3),但代码仅在分割后长度为2时才处理,直接跳过了所有有效输入。 - main方法的循环中重复定义了
String[] currencies变量,属于编译错误,程序根本无法正常运行。
- 用户输入的每个汇率对包含三个字段(如
未加载用户输入的汇率:代码硬编码了固定的汇率数据,完全忽略了用户输入的汇率对,导致计算时无法使用题目给出的USD→GBP→JPY这条最优路径。
无兑换路径时返回错误值:如果找不到兑换路径,方法会返回-1.0,这不符合预期,应该返回当前持有的金额(无法兑换时保持原货币)。
未处理循环兑换:没有标记已访问的货币,可能导致无限递归(如USD→CAD→USD)。
修复后的完整代码
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8); BufferedReader in = new BufferedReader(reader); Map<String, Double> fxRates = new HashMap<>(); String line; // 读取并解析用户输入的汇率对 while ((line = in.readLine()) != null) { String[] currencyPairs = line.split(";"); for (String pair : currencyPairs) { String[] parts = pair.trim().split(","); if (parts.length == 3) { String from = parts[0].trim(); String to = parts[1].trim(); double rate = Double.parseDouble(parts[2].trim()); // 添加正向汇率 fxRates.put(from + ", " + to, rate); // 添加反向汇率(支持双向兑换) fxRates.put(to + ", " + from, 1.0 / rate); } } } // 计算1单位USD兑换JPY的最大金额(符合题目预期场景) double result = calculateMaxAmount(fxRates, "USD", "JPY", 1.0, new HashSet<>()); System.out.println(result); } // 增加visited集合防止循环兑换 public static double calculateMaxAmount(Map<String, Double> fxRates, String currentCurrency, String targetCurrency, double amount, Set<String> visited) { // 到达目标货币,返回当前金额 if (currentCurrency.equals(targetCurrency)) { return amount; } // 已访问过当前货币,避免循环 if (visited.contains(currentCurrency)) { return -1.0; } visited.add(currentCurrency); double maxAmount = amount; // 默认返回当前金额(无法兑换时) for (Map.Entry<String, Double> entry : fxRates.entrySet()) { String[] currencies = entry.getKey().split(","); String from = currencies[0].trim(); String to = currencies[1].trim(); double rate = entry.getValue(); if (from.equals(currentCurrency)) { Set<String> newVisited = new HashSet<>(visited); double tempAmount = calculateMaxAmount(fxRates, to, targetCurrency, amount * rate, newVisited); if (tempAmount > maxAmount) { maxAmount = tempAmount; } } } visited.remove(currentCurrency); return maxAmount; } }
修复说明
- 修正了
calculateMaxAmount的参数传递顺序,确保起始货币和目标货币匹配。 - 重构输入解析逻辑,正确读取用户输入的三元组汇率对,并将其加入汇率表,同时添加反向汇率以支持双向兑换。
- 增加
visited集合记录已访问的货币,避免无限递归和循环兑换。 - 调整无路径时的返回值为当前持有金额,保证结果符合预期。
- 移除了硬编码的无效汇率数据,完全使用用户输入的汇率进行计算。
内容的提问来源于stack exchange,提问作者Neha M
相关产品推荐
相关产品推荐

