0

我非常接近完成我的任务,但我不知道如何findChange()正确调用。我的猜测是它需要在 main 方法中。但是当 findChange(); 打电话给它,它要求int, List<Integer>, List<Integer>我如何“正确”地做到这一点。

代码

import java.io.*;
import java.util.*;
import java.lang.*;

public class homework5 {

    public static int change;

    public static void main(String[] args)
        throws FileNotFoundException 
    { //begin main

        ArrayList<Integer> coinTypes = new ArrayList<Integer>();//array to store
        //coin types

        Integer i;
        File f = new File (args[0]);
        Scanner input = new Scanner(f); //initialize scanner
        input.nextLine();
        while(input.hasNextInt()) {
            i = input.nextInt();
            coinTypes.add(i);
        }
        change = coinTypes.get(coinTypes.size()-1); //this will add all ints
        coinTypes.remove(coinTypes.size()-1);
        System.out.println("Found change"); //used for debugging
        System.out.println("Change: " + change);

        //findChange(); ideal spot to call the method
        //System.out.println(coinTypes);
    }

    boolean findChange(int change, List<Integer> coinTypes,
                       List<Integer> answerCoins) 
    { //contains means of
        //finding the change solutions
        if(change == 0) {
            return true; //a solution
        }
        if(change < 0) {
            return false; //if negative it can't be a solution
        } else {
            for(Integer coin : coinTypes) {
                if(findChange(change - coin, coinTypes, answerCoins)){
                    answerCoins.add(coin); //if it works out add it to the
                    return true;         //solution List
                }
            }

        }

        List<Integer> answer = new ArrayList<Integer>();
        boolean canFindChange = findChange(change, coinTypes, answer);
        if(canFindChange) { //if there is a solution, print it
            System.out.println(answer);
        } else { System.out.println("No change found");
        }
        return false; //else return false
    }

}

这个程序计算了所有不同的方式来显示一定金额的变化,即:143(1.43 美元)。我所要做的就是调用findChange()main 并且它应该可以工作,我错过了什么?

编辑我刚刚意识到我没有指定我需要帮助的方法调用我为任何不清楚的地方道歉

输入文件

// Coins available in the USA, given in cents.  Change for $0.09?
1 5
9

电流输出

Change: 9

Change: 9
['solutions to all possible combinations to make $0.09']
4

0 回答 0