Java硬币改变输出奇怪的值[不作业]

时间:2013-05-13 20:04:07

标签: java

我正在尝试让我的硬币更改算法正常工作......但它输出了奇怪的结果...... 它应该枚举所有输入金额的变化排列。

输入27美分,printValues(dan.makeChange(27));让我:

[[3, 300, 1386, 4720], [3, 300, 1386, 4720], [3, 300, 1386, 4720],etc...

7美分的输入让我:

[[0, 0, 3, 10], [0, 0, 3, 10], [0, 0, 3, 10], [0, 0, 3, 10]]

代码:

public List<int[]> makeChange(int change) {
    List<int[]> resultsList = new ArrayList<int[]>();
    resultsList = changeMaker(change, new int[] {0,0,0,0}, resultsList);
    return resultsList;
}

public List<int[]> changeMaker(int change, int[] toAdd, List<int[]> resultsList) {               
    if (change == 0) {
        //if no $, return the list...
        resultsList.add(toAdd);
        return resultsList;
    }
    int[] coins = {25, 10, 5, 1};
    for (int i = 0; i < coins.length; i++) {
        if (coins[i] <= change) {
            //temp = {0, 0, 0, 0}
            int[] temp = toAdd;
            //move to next amount in temp array
            temp[i]++;
            resultsList = changeMaker(change-coins[i], temp, resultsList);
        }
    }
    return resultsList;
}

呼叫:

    printValues(dan.makeChange(27));            
}
public void printValues (List<int[]> results) {
    List<String> printable = new ArrayList<String> ();

    for (int[] array : results) {
        printable.add(Arrays.toString(array));
    }
    System.out.println(printable);
}

有什么想法?

1 个答案:

答案 0 :(得分:2)

我假设你想用这一行复制数组:

int[] temp = toAdd;

但是,要创建副本,您必须这样做:

int[] temp = Arrays.copyOf(toAdd, toAdd.length);