如何使用这种方法?

时间:2014-11-24 06:48:46

标签: java method-call recursive-backtracking

我非常接近完成任务,但我无法弄清楚如何正确地呼叫findChange()。我的猜测是它需要在主方法中。但是当findChange();打电话给它,它要求int, List<Integer>, List<Integer>所以如何“正确”这样做呢。

CODE

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)。我要做的就是给{main} findChange()打电话,它应该有用,我错过了什么?

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

INPUT FILE

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

当前输出

Change: 9

WANT

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

0 个答案:

没有答案