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

如何修改Java零钱兑换函数实现从URL读取数值并将结果写入result.txt

解决方案

修改后的可直接运行的完整代码如下:

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

public class MinBillsCalculator {
    public static void main(String[] args) throws IOException {
        try {
            URL url = new URL("http://cei.edu.uy/plata.txt");
            try (Scanner s = new Scanner(url.openStream())) {
                File f = new File("result.txt");
                try (PrintStream print = new PrintStream(f)) {
                    int bills[] = {2000, 1000, 500, 200, 100,50, 20, 10, 5, 2, 1};
                    int m = bills.length;
                    // 循环读取URL中的每一个数值
                    while (s.hasNextInt()) {
                        int V = s.nextInt();
                        int res = minBills(bills, m, V);
                        // 结果同时输出到控制台和result.txt
                        String output = String.format("金额%d需要的最少纸币张数:%d", V, res);
                        System.out.println(output);
                        print.println(output);
                    }
                    print.flush();
                }
            }
        } catch (MalformedURLException ex) {
            System.err.println("URL格式错误:" + ex.getMessage());
        } catch (IOException ex) {
            System.err.println("资源读取/文件写入错误:" + ex.getMessage());
        }
    }

    static int minBills(int bills[], int m, int V)
    {
        int table[] = new int[V + 1];
        table[0] = 0;
        for (int i = 1; i <= V; i++)
            table[i] = Integer.MAX_VALUE;

        for (int i = 1; i <= V; i++)
        {
            for (int j = 0; j < m; j++)
                if (bills[j] <= i)
                {
                    int sub = table[i - bills[j]];
                    if (sub != Integer.MAX_VALUE
                            && sub + 1 < table[i])
                        table[i] = sub + 1;
                }
        }
        if(table[V]==Integer.MAX_VALUE)
            return -1;
        return table[V];
    }
}

改动说明

  • 移除了手动写死的金额变量V = 153,改为从URL输入流中逐个读取数值作为参数传入计算方法
  • 补充了空异常块的错误日志输出,方便定位运行问题
  • 将while (s.hasNext())修改为while (s.hasNextInt()),过滤非整数内容避免运行报错

内容的提问来源于stack exchange,提问作者Martin Aguilar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 18:03:00