Write a program in Java which: 1. Prompts the user to enter a positive integer.
ID: 3799885 • Letter: W
Question
Write a program in Java which:
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.
5. The user must be allowed to continue entering numbers unless (s)he chooses to quit.
The program’s display must adhere to the following rules:
1. One “coin” per line.
2. Proper use of the singular or plural nouns; example 1 dime or 2 dimes.
3. Only display coins that are actually used in the result.
Explanation / Answer
CoinsTest.java
import java.util.Scanner;
public class CoinsTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("Enter a positive integer(-1 to quit): ");
int amount = scan.nextInt();
if(amount == -1){
break;
}
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");
}
}
}
}
}
Output:
Enter a positive integer(-1 to quit):
99
3 quarters
2 dimes
4 pennies
Enter a positive integer(-1 to quit):
96
3 quarters
2 dimes
1 penny
Enter a positive integer(-1 to quit):
79
3 quarters
4 pennies
Enter a positive integer(-1 to quit):
26
1 quarter
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.