In: Computer Science
The user will input a dollar amount as a floating point number; read it from input using a Scanner and the .nextDouble() method. Convert the number of dollars into a number of whole (integer) cents, e.g., $1.29 = 129 cents. Determine and output the optimal number of quarters, dimes, nickels, and pennies used to make that number of cents.
Ex: if the input is
1.18
The output should be
4 1 1 3
for 4 quarters, 1 dime, 1 nickel, 3 pennies.
Hints
(STARTING CODE)
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/* Type your code here. */
}
}
Hello,
Please find the below code and inline comments:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
int leftover; /* used to hold
amount as it decreases */
int numquarters; /* how many
quarters */
int numdimes; /* how many dimes
*/
int numnickels; /* how many nickels
*/
int numpennies; /* how many pennies
*/
Scanner input = new Scanner(System.in);
double dollars; // Total value of all the coins, in dollars.
/* Ask the user for the number of each type of coin. */
System.out.print("Enter the
dollars? :");
dollars = input.nextDouble();
int cents = (int) Math.round(100 *
dollars);
// System.out.println(cents);
leftover = cents;
numquarters = leftover /
25;
leftover = leftover % 25;
/* computer the number of dimes
and how much is left over */
numdimes = leftover / 10;
leftover = leftover % 10;
/* computer the number of nickels
and how much is left over */
numnickels = leftover / 5;
leftover = leftover % 5;
/* whatever is left over is the
number of pennies */
numpennies = leftover;
/* print the result */
System.out.println(numquarters);
System.out.println(numdimes);
System.out.println(numnickels);
System.out.println(numpennies);
}
}
Project Structure:
Test Result:
Let me know if you have any doubts in the comments sections.
Thanks