-1

我得到了一个不兼容的类型,需要 int found:void on this line --> moneyCount = countDemoninations(change, denomination[i])。试图理解为什么?

public class Change {
    int [] denomination = {1,2,5,10,20,50,100,200,500,1000,2000,5000};
    int moneyCount = 0; 

    public void catagorizeChange(int change){
        for (int i = 0; i < denomination.length; i++){
            moneyCount = countDemoninations(change, denomination[i]);

        }
    }   

    public void countDemoninations(int change, int denomination){
        int moneyCount =0;
        while (change >= denomination){
            moneyCount = moneyCount++;
            change = change - denomination;
        }
    }
}

我是一个新的java学生,我想知道下面的编辑代码是否在一个好的实践中,即在另一个属于同一个类的情况下使用一种方法?

    public void countChangedenominations (int change){
        for (int i = 0; i < moneyValuearray.length; i++){
            moneyCountarray[i] = countDemonination(change, moneyValuearray[i]);
        }
    }   

    public int countDemonination(int change, int denomination){
        while (change >= denomination){
            moneyCount = ++moneyCount;
            change = change - denomination; 
        }
        return moneyCount;   
4

1 回答 1

1

线路问题的根源:

moneyCount = countDemoninations(change, denomination[i]);

is thatcountDemoninationsvoid类型,而moneyCount是 类型int

要解决此问题,请将您的countDemoninations方法签名更改为 returnint而不是void,然后moneyCount作为方法中的最后一条语句返回:

public int countDemoninations( int change, int denomination ) {
    int moneyCount = 0;
    while ( change >= denomination ) {
        moneyCount = moneyCount++;
        change = change - denomination;
    }

    return moneyCount;
}
于 2012-10-19T22:31:05.457 回答