The program below is the solution to Liang’s Introduction to Java Programming (9th Edition) Chapter 2 Exercise 2.24.

Question: Rewrite Listing 2.10, ComputeChange.java, to fix the possible loss of accuracy when converting a double value to an int value. Enter the input as an integer whose last two digits represent the cents. For example, the input 1156 represents 11 dollars and 56 cents.

1 2 |
/**<br /> *<br /> * @Author: Aghatise Osazuwa<br /> * Website: www.cscprogrammingtutorials.com<br /> *<br /> * Exercise 2.24 - Financial application: monetary units<br /> *<br /> */ <br /><br />import java.util.Scanner;<br /><br />public class ComputeChange {<br /><br /> public static void main(String[] args) {<br /> <br /> Scanner input = new Scanner(System.in);<br /> System.out.print("Enter an amount, for example, 1156 for $11.56: ");<br /> int amount = input.nextInt();<br /> int remainingAmount = amount;<br /> int numberOfOneDollars = remainingAmount / 100;<br /> remainingAmount = remainingAmount % 100;<br /> // Find the number of quarters in the remaining amount<br /> int numberOfQuarters = remainingAmount / 25;<br /> remainingAmount = remainingAmount % 25;<br /> // Find the number of dimes in the remaining amount<br /> int numberOfDimes = remainingAmount / 10;<br /> remainingAmount = remainingAmount % 10;<br /> // Find the number of nickels in the remaining amount<br /> int numberOfNickels = remainingAmount / 5;<br /> remainingAmount = remainingAmount % 5;<br /> // Find the number of pennies in the remaining amount<br /> int numberOfPennies = remainingAmount;<br /> // Display results<br /> System.out.println("nYour amount " + amount + " consists of: t" <br /> + numberOfOneDollars + " dollarsn"<br /> + "tttt" + numberOfQuarters + " quartersn"<br /> + "tttt" + numberOfDimes + " dimesn"<br /> + "tttt" + numberOfNickels + " nickelsn"<br /> + "tttt" + numberOfPennies + " pennies");<br /> }<br />}<br /> |

Program Output |

Click here to see other solutions to Introduction to Java Programming.