/**
* Generates a random number as a price of an item, calculates how much change given if paid for using a 20 dollar bill, and calculates how many dollars, quarters, and nickels used.
*
* @Laura
* @1.0
*/
import java.lang.Math.*;
public class MakeChange
{
public static void main(String[] args) {
double randomNumber = 0; //initializing values
double price = 0;
double change = 0;
double changeCoins = 0;
int dollars = 0;
int quarters = 0;
int dimes = 0;
int pennies = 0;
randomNumber = Math.random() * 18 + 1; //generates a random number between 1 and 18
price = Math.round(randomNumber * 100.0)/100.0; //rounds the number to 2 decimal places
System.out.println("The price of the item is $" + price + "."); //outputs the rounded price
change = Math.round((20 - price) * 100.0)/100.0; //rounded again to prevent error from leftover price decimals
System.out.println("You will receive $" + change + " in change."); //ouputs the change if you pay with a 20 dollar bill
changeCoins = change * 100; //converts the change (which is in dollars and cents) to only coins
dollars = (int)(changeCoins/100); //sets dollars to highest number of times the change in cents can be divided by 100 without a decimal
changeCoins %= 100; //sets changeCoins to the remainder when divided by 100 (how much is left over after getting change back in dollars)
quarters = (int)(changeCoins/25);
changeCoins %= 25;
dimes = (int)(changeCoins/10);
changeCoins %= 10;
pennies = (int) changeCoins;
System.out.println("That is " + dollars + " dollars, " + quarters + " quarters, " + dimes + " dimes, and " + pennies + " pennies."); //outputs change in each coin
System.out.println("Program terminated.");
}
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.