只允许一个实例字段但需要更多?

时间:2011-10-16 00:42:50

标签: java

我是一名学生,正在努力完成我老师的特定实验课程。我尝试在Jcreator中编译时出现问题,我收到错误,找不到符号。我认为这是因为我没有创造“美元”和“美分”。老师说学生只能有一个实例字段,所以如何解决这个问题呢?

编辑:谢谢,我修复了模数运算符并将返回值放入。

我在“int dollars =(int)total / PENNIES_PER_DOLLAR_VALUE;”中收到错误line和“int cents = total%PENNIES_PER_DOLLAR_VALUE;”。

由于

 public class CoinCounter
 {
    // constants
    //*** These are class constants so they need public static
    public static final int QUARTER_VALUE = 25;
    public static final int DIME_VALUE = 10;
    public static final int NICKEL_VALUE = 5;
    public static final int PENNY_VALUE = 1;
    public static final int PENNY_PER_DOLLAR_VALUE = 100;

    // instance field (one - holds the total number of cents EX:  8,534)
    private int total;

    /**
     * Constructs a CoinCounter object with a specified number of pennies,
     * nickels, dimes and quarters
     * @param quarterAmount the amount of quarters
     * @param dimeAmount the amount of dimes
     * @param nickelAmount the amount of nickels
     * @param pennyAmount the amount of pennies
     */
    public CoinCounter(int quarters, int dimes, int nickels, int pennies)
    {
        total = quarters * QUARTER_VALUE + nickels * NICKEL_VALUE + dimes * DIME_VALUE + pennies;

    }
    // add remaining methods as described

    /**
     * getDollars returns the number of dollars in the CoinCounter
     *  @return the number of dollars
    */
    public int getDollars()
    {
        int dollars = (int) total / PENNIES_PER_DOLLAR_VALUE;
            return dollars;
    }
    /**
     * getCents returns the number the numbers of cents left over after the dollars are removed
     *  @return the number of cents left over
    */
    public int getCents()
    {
        int cents = total % PENNIES_PER_DOLLAR_VALUE;
            return cents;
    }


 }

2 个答案:

答案 0 :(得分:1)

getDollars()getCents()方法声明返回int时,它们没有返回任何内容。

public int getDollars()
{
    int dollars = (int) total / PENNIES_PER_DOLLAR_VALUE;
    return dollars;
}

public int getCents()
{
    int cents = total % PENNIES_PER_DOLLAR_VALUE;
    return cents;
}

修改

问题是你的常数的命名。

你定义这个:

public static final int PENNY_PER_DOLLAR_VALUE = 100;

但你用这个:

PENNIES_PER_DOLLAR_VALUE

答案 1 :(得分:1)

您创建了一个名为PENNY_PER_DOLLAR_VALUE的常量:

public static final int PENNY_PER_DOLLAR_VALUE = 100;

但后来你引用了PENNIES_PER_DOLLAR_VALUE:

int dollars = (int) total / PENNIES_PER_DOLLAR_VALUE;

int cents = total % PENNIES_PER_DOLLAR_VALUE;

这是它找不到的符号。