Search code examples
javaclassintdriversystem.out

Java Coin Counter Quarters/Dimes/Nickels/Pennies


I've been having trouble with this one program I'm trying to run.

This lab will investigate the problem solving and programming behind such machinery.

You always want to use the fewest coins possible. You should use integer mathematics to solve this problem.

Provide the number of cents through the constructor. Write a method that calculates the number of each type of coin.

tl;dr I need to count coins in a certain amount of cents.

so far, I have this:

public class P4_Icel_Murad_Coins_java{
    private int c;
    public P4_Icel_Murad_Coins_java(int coins){
        c = 94;
        int Q_i, D_i, N_i, N_f;
    }

    public void counter(){
        int Q_i = (int)(c % 25);
        int Q_f = c - (Q_i * 25);
        int D_i = (int)(Q_f % 10);
        int D_f = c - (D_i * 10);
        int N_i = (int)(D_f % 5);
        int N_f = (int)(c - (N_i * 5));

        System.out.println("Quarter(s): " + Q_i );
        System.out.println("Dime(s): " + D_i);
        System.out.println("Nickel(s): " + N_i);
        System.out.println("Penny(ies): " + N_f);               

    }
}

And my Driver class is

public class Driver_class
{
    public static void main(String[] args) {
        P4_Icel_Murad_Coins_java start = new P4_Icel_Murad_Coins_java(94);
        start.counter();
    }
}

I am getting really odd numbers that include negatives in the answer, and alot of pennies for some reason. Any help will be appreciated, and thanks in advance.


Solution

  • You have to use divide "/" instead of modulo "%". E.g.

    int Q_i = (int)(c / 25);
    

    And you should correct your constructor, which didn't use the coins from caller:

    public P4_Icel_Murad_Coins_java(int cents){
        c = cents; // here use the caller cents
    }