So I'm trying to write a code that will help solve this problem:
Develop a Java program that computes which bills and coins will be given as change for a sales transaction.
Available bills are:
$20
$10
$5
$1
Available coins are:
quarter (25 cents)
dime (10 cents)
nickel (5 cents)
penny (1 cent)
Only print the actual bills and coins returned. Do not print unused denominations (for example, if no $10 bills are returned, do not print anything regarding $10 bills).
Example:
What is the total sales charge? 58.12
How much is the customer giving? 100.00
The change is:
2 $20 bills
1 $1 bill
3 quarters
1 dime
3 pennies
Here's the code that I wrote:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner uinput = new Scanner(System.in);
double paid;
double cost;
double change;
int onebills = 0;
int fivebills = 0;
int tenbills = 0;
int twentybills = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
System.out.println("What is the total sales charge?");
cost = uinput.nextDouble();
System.out.println("");
System.out.println("How much is the customer giving?");
paid = uinput.nextDouble();
change = paid - cost;
while(change >= 20) { //if the change is more than $20, give a 20 dollar bill
change -= 20;
twentybills++;
}
while(change >= 10) { //if the change is more than $10, give a 10 dollar bill
change -= 10;
tenbills++;
}
while(change >= 5) { //if the change is more than $5, give a 5 dollar bill
change -= 5;
fivebills++;
}
while(change >= 1) { //if the change is more than $1, give a 1 dollar bill
change -= 1;
onebills++;
}
while(change >= 0.25) { //if the change is more than $0.25, give a quarter
change -= 0.25;
quarters++;
}
while(change >= 0.10) { //if the change is more than $0.10, give a dime
change -= 0.10;
dimes++;
}
while(change >= 0.05) { //if the change is more than $0.05, give a nickel
change -= 0.05;
nickels++;
}
while(change >= 0.01) { //if the change is more than $0.01, give a penny
change -= 0.01;
pennies++;
}
System.out.println("");
if(twentybills > 0) {
System.out.println(twentybills + " twenty dollar bills");
}
if(tenbills > 0) {
System.out.println(tenbills + " ten dollar bills");
}
if(fivebills > 0) {
System.out.println(fivebills + " five dollar bills");
}
if(onebills > 0) {
System.out.println(onebills + " one dollar bills");
}
if(quarters > 0) {
System.out.println(quarters + " quarters");
}
if(dimes > 0) {
System.out.println(dimes + " dimes");
}
if(nickels > 0) {
System.out.println(nickels + " nickels");
}
if(pennies > 0) {
System.out.println(pennies + " pennies");
}
} }
For the most part, my code seems to work. However, when I input a sales charge of 99.01 and the customer gives 100, I'm missing one penny. I have absolutely no idea what happened to cause that missing penny.
This is what I end up with: 3 quarters 2 dimes 3 pennies
If anyone can help me find the issue, that would be greatly appreciated! I'm only a high school student learning Java so I don't know much...