CoinCounter实验室

时间:2013-11-17 16:12:06

标签: java swing joptionpane

我是java的初学者。当我上课时&测试员,没有错误,但我没有从测试仪获得我想要的输出。我找不到我做错了什么。请帮忙

这是我的代码:

/**
 * A CoinCounter has a specific number of cents.  It can provide the number of dollars and the
 * number of cents that it contains
 */
 public class CoinCounter
{
// constants
    public static final int PENNIES_PER_NICKEL = 5;
    public static final int PENNIES_PER_DIME = 10;
    public static final int PENNIES_PER_QUARTER = 25;
    public static final int PENNIES_PER_DOLLAR = 100;

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

/**
 * Constructs a CoinCounter object with a specified number of pennies, nickels, dimes and quarters
 * @param pennies number of pennies
 * @param nickels number of nickels
 * @param dimes number of dimes
 * @param quarters numbr of quarters
 */
public CoinCounter(int pennies, int nickels, int dimes, int quarters)
/**
 * Computes the total value in pennies
 */
{
    int totalCents = pennies + nickels * PENNIES_PER_NICKEL + dimes * PENNIES_PER_DIME + quarters * PENNIES_PER_QUARTER;
}
// ACCESSOR methods as described (only two)
/**
 * Gets the number of dollars
 * @return number of dollars
 */
public int getDollars()
{
    int dollars = totalCents / PENNIES_PER_DOLLAR;
    return dollars;
}

/**
 * Gets the number of cents
 * @return number of cents
 */
public int getCents()
{
    int cents = totalCents % PENNIES_PER_DOLLAR;
    return cents;
}
//MUTATOR METHODS - NONE FOR THIS PROGRAM

这是我的测试员:

import javax.swing.JOptionPane;
/**
* A class to test the CoinCounter class
*/
public class CoinCounterTester
{
/**
* Tests methods of the CoinCounter class
* @param args not used
*/
public static void main(String[] args)
{
// Use JOptionPane to read in coins
    String input = JOptionPane.showInputDialog("Please enter the number of pennies: ");
    int pennies = Integer.parseInt(input);  

    input = JOptionPane.showInputDialog("Please enter the number of nickels: ");
    int nickels = Integer.parseInt(input);

    input = JOptionPane.showInputDialog("Please enter the number of dimes: ");
    int dimes = Integer.parseInt(input);

    input = JOptionPane.showInputDialog("Please enter the number of quarters: ");
    int quarters = Integer.parseInt(input);

    // Construct an object 
        CoinCounter myCoins = new CoinCounter(22, 8, 17, 5);
    //Call the TWO ACCESSOR METHODS-print dollars & cents
        System.out.println("The total dollars is: " + myCoins.getDollars());
        System.out.println("The total cents is:   " + myCoins.getCents());

        System.exit(0);
    //NO MUTATOR METHODS to test     
}
}

运行测试仪并输入每个硬币的数量后,我的输出是

  • 总金额为:0
  • 总分为:0

而不是

  • 总金额为:3
  • 总分为:57

我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:2)

变化

int totalCents = pennies + nickels * PENNIES_PER_NICKEL....

 this.totalCents = pennies + nickels....