Answer to Question #322401 in Java | JSP | JSF for Dave

Question #322401

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.


1
Expert's answer
2022-06-28T08:19:28-0400
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"));
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS