Write a program with total change amount in pennies as an integer input, and output the change using the fewest coins, one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. Use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies.
import java.util.Scanner;
public class Main {
public static void main(String[] arguments) {
try (Scanner scanner = new Scanner(System.in)) {
int pennies = scanner.nextInt();
int dollars = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
while (pennies >= 100) {
pennies -= 100;
dollars++;
}
while (pennies >= 25) {
pennies -= 25;
quarters++;
}
while (pennies >= 10) {
pennies -= 10;
dimes++;
}
while (pennies >= 5) {
pennies -= 5;
nickels++;
}
if (dollars > 0)
System.out.println(dollars + " " + (dollars == 1 ? "Dollar" : "Dollars"));
if (quarters > 0)
System.out.println(quarters + " " + (quarters == 1 ? "Quarter" : "Quarters"));
if (dimes > 0)
System.out.println(dimes + " " + (dimes == 1 ? "Dime" : "Dimes"));
if (nickels > 0)
System.out.println(nickels + " " + (nickels == 1 ? "Nickel" : "Nickels"));
if (pennies > 0)
System.out.println(pennies + " " + (pennies == 1 ? "Penny" : "Pennies"));
}
}
}
Comments
Leave a comment