# Thread: Need to make a program that gives exact change

1. Member
Join Date
Sep 2014
Posts
1
Rep Power
0

## Need to make a program that gives exact change

So obviously I'm new to java and i need to write a program that gives exact change in quarters, dimes, nickels, and pennies. For some reason it seems to work correctly but the nickels never is correct and I'm not sure why, seeing as though everything else is.

Java Code:
```public class Coins{
private int c;

public  Coins(int coins){
c = coins;
}

public void calculate(){
int quarters = c / 25;
System.out.println("quarters = " + quarters);
int dimes = (c%25) / 10;
System.out.println ("dimes = " + dimes);
int nickels = (c%10) / 5;
System.out.println ("nickels = " + nickels);
int pennies = (c%5) / 1;
System.out.println ("pennies = " + pennies);
}
}```
thanks in advance for any help with this i'm not sure what i'm doing wrong

2. ## Re: Need to make a program that gives exact change

Do some calculations by hand: let c == 25 (one quarter); your algorithm finds one quarter, zero dimes, two nickels and five cents ... check your code ...

kind regards,

Jos

3. ## Re: Need to make a program that gives exact change

Actually it won't find 5 pennies ;)

4. Member
Join Date
Aug 2011
Location
Cornwall, UK
Posts
25
Rep Power
0

## Re: Need to make a program that gives exact change

c is a local variable set to the value of the coins argument, as such it can (and should) be set to new values as appropriate for each line of your code.

Initially it is correctly set to coins and used in your first line of int quarters = c/25;

It should then be set to the value remaining using c = c%25; with the next line as int dimes = c/10

You can combine these two lines of code as you have done in your int d = (c%25)/10 but I would not.

Using a reset approach of c, your next lines of code would be
c = c%10
int nickels = c/5
int pennies c%5

You could continue with a multi % approach
int nickels = ((c%25)%10)/5 'might work
int pennies = (((c%25)%10)%5) 'might work

These last two lines emphasise the need to keep coding simple to read and understand code (KISS), I have not got Java open so cannot test the multi % code suggested but I know that resetting the c value each time does work as Jos intimated check your code and Keep It Simple Stupid

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•