Hello, Please help write program that calculates coins in Java Program should do
ID: 3834804 • Letter: H
Question
Hello,
Please help write program that calculates coins in Java
Program should do the following:
1) Prompts the user to enter a positive integer.
2) The program should calculate the least possible number of coins and display the result.
3) The program MUST display the results using proper grammar (singular or plural).
4) The program MUST validate the user input and NOT allow ANYTHING that is not an integer greater than or equal to zero.
The program’s display must adhere to the following rules:
One “coin” per line.
Proper use of the singular or plural nouns; example 1 dime or 2 dimes.
Only display coins that are actually used in the result.
Acceptable display examples include:
2 quarters
1 dime
1 penny
2 dimes
1 nickel
4 pennies
1 quarter
3 pennies
UNACCEPTABLE examples include:
2 quarter(s)
1 dime(s)
1 nickel
1 penny
1 quarter
0 dimes
0 nickels
3 pennies
GENERAL RESTRICTIONS
No break statements to exit loops
Thank you
2 quarters
1 dime
1 penny
Explanation / Answer
CoinsTest.java
import java.util.Scanner;
public class CoinsTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive integer(-1 to quit): ");
int amount = scan.nextInt();
while(amount !=-1){
if(amount <=0 ){
System.out.print("Invalid Input. ");
}
else{
int quarters = amount / 25;
amount = amount % 25;
int dimes = amount/ 10;
amount = amount % 10;
int nickels = amount / 5;
amount = amount % 5;
int penny = amount;
if(quarters != 0){
if(quarters == 1)
System.out.println(quarters+" quarter");
else
System.out.println(quarters+" quarters");
}
if(dimes != 0){
if(dimes == 1)
System.out.println(dimes+" dime");
else
System.out.println(dimes+" dimes");
}
if(nickels != 0){
if(nickels == 1)
System.out.println(nickels+" nickel");
else
System.out.println(nickels+" nickels");
}
if(penny != 0){
if(penny == 1)
System.out.println(penny+" penny");
else
System.out.println(penny+" pennies");
}
}
System.out.println("Enter a positive integer(-1 to quit): ");
amount = scan.nextInt();
}
}
}
Output:
Enter a positive integer(-1 to quit):
89
3 quarters
1 dime
4 pennies
Enter a positive integer(-1 to quit):
-5
Invalid Input. Enter a positive integer(-1 to quit):
99
3 quarters
2 dimes
4 pennies
Enter a positive integer(-1 to quit):
6
1 nickel
1 penny
Enter a positive integer(-1 to quit):
-1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.