In: Computer Science
Program in Java code
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.
.Ex1: If the input is: 0
the output is: No change
Ex2: If the input is: 45
the output is: 1 Quarter
2 Dimes
import java.util.Scanner;
public class Convert {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// reading number of pennies
System.out.print("Enter change amount in pennies : ");
int amount = sc.nextInt();
int remaining = amount;
// calculating number of dollars
int dollars = remaining/100;
remaining = remaining % 100;
// calculating number of quarters
int quarters = remaining / 25;
remaining = remaining % 25;
// calculating number of dimes
int dimes = remaining / 10;
remaining = remaining % 10;
// calculating number of nickels
int nickels = remaining / 5;
remaining = remaining % 5;
// calculating number of pennies
int pennies = remaining ;
// if currency is greater than zero then print that currency
// in singular and plural
if(dollars > 0) {
System.out.println(dollars==1?"1 Dollar":dollars+" Dollars");
}
if(quarters > 0) {
System.out.println(quarters==1?"1 Quarter":quarters+" Quarters");
}
if(dimes > 0) {
System.out.println(dimes==1?"1 Dime":dimes+" Dimes");
}
if(nickels > 0) {
System.out.println(nickels==1?"1 Nickel":nickels+" Nickels");
}
if(pennies > 0) {
System.out.println(pennies==1?"1 Penny":pennies+" Pennies");
}
// checking if all are zeros and prints no change
if(dollars ==0 && quarters ==0&& dimes==0&&nickels==0&&pennies==0) {
System.out.println("No change");
}
sc.close();
}
}
Code
Output
Testcase #1
Testcase #2
Testcase #3