I am working on a java assignment where you enter the price of an object and the amount a theoretical customer handed you for the item. Then the program returns how much you owe them, and breaks it down into dollars, quarters, dimes, nickles, and pennies that you should give them.
Basically here's what it would look like when it runs
What was the purchase price? (exclude the decimal in calculation if it helps
you)
$98.50
How much money did you pay with? (exclude the decimal)
$100.00
The purchase price was $98.50
You payed $100.0
You received $1.50 in change.
0 one hundred dollar bill(s)
0 fifty dollar bill(s)
0 twenty dollar bill(s)
0 ten dollar bill(s)
0 five dollar bill(s)
1 one dollar bill(s)
2 quarter(s)
0 dime(s)
0 nickel(s)
0 penny/pennies
I understand most of it, but I cant seem to wrap my mind around the breakdown of the change handed back. Here's my code so far, but if someone could show me how to break down the change.
import java.util.*;
public class ChangeTendered {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the purchase price: ");
double price = scan.nextDouble();
System.out.println("Enter the amount payed: ");
double ammountPayed = scan.nextDouble();
double changeDue = ammountPayed - price;
int dollars = (int)changeDue;
System.out.println("Return"+ dollars+ "Dollars");
scan.close();
}
}
On a side note, I just cast the changeDue to an int in order to chop off the decimal and get the dollars due, if that caused any confusion.
Here is an initial approach
int change = (int)(Math.ceil(changeDue*100));
int dollars = Math.round((int)change/100);
change=change%100;
int quarters = Math.round((int)change/25);
change=change%25;
int dimes = Math.round((int)change/10);
change=change%10;
int nickels = Math.round((int)change/5);
change=change%5;
int pennies = Math.round((int)change/1);
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
You can add more code to the do it for currency notes as well.
From what I can understand, you need to break the returned money into different bills: 100, 50, 20, 10, 5 ... etc.
I think you can use 'division' to solve the problem in Java. The following pseudo code is how you might solve the problem:
//For example:
double changeDue = 15.5;
double moneyLeft = changeDue;
int oneHundred = moneyLeft / 100;
moneyLeft -= oneHundred * 100;
int fifty = moneyLeft / 50;
moneyLeft -= fifty*50 ;
...
//Just remember to 'floor' the result when divided by a double value:
int quarter = Math.floor( moneyLeft / 0.25);
moneyLeft -= quarter * 0.25 ;
...//Until your minimum requirement.
//Then print out your results.
Hope it helps.
What I did was convert it to a string then do a decimal split to separate the change and dollars.
import java.util.Scanner;
import java.text.DecimalFormat;
public class register
{
public static void main(String[] args)
{
DecimalFormat decimalFormat = new DecimalFormat("0.00");
Scanner kb = new Scanner(System.in);
System.out.print("How much does this item cose? -> ");
double cost = kb.nextDouble();
System.out.print("How many will be purcased? -> ");
double quanity = kb.nextDouble();
double subtotal = (cost * quanity);
double tax = (subtotal * .06);
double total = (subtotal + tax);
System.out.print("How much money has been tendered? -> ");
double tendered = kb.nextDouble();
double change = (tendered - total);
int dollars = (int)change;
int twenties = dollars / 20;
int dollars1 = dollars % 20;
int tens = dollars1 / 10;
int dollars2 = dollars % 10;
int fives = dollars2 / 5;
int dollars3 = dollars % 5;
int ones = dollars3;
String moneyString = decimalFormat.format(change);
String changeString = Double.toString(change);
String[] parts = moneyString.split("\\.");
String part2 = parts[1];
double cents5 = Double.parseDouble(part2);
int cents = (int)cents5;
int quarters = cents / 25;
int cents1 = cents % 25;
int dimes = cents1 / 10;
int cents2 = cents % 10;
int nickels = cents2 / 5;
int cents3 = cents % 5;
int pennies = cents3;
System.out.println("Cost: " + "$" + decimalFormat.format(cost));
System.out.println("Quanity: " + quanity);
System.out.println("Subtotal: " + "$" + decimalFormat.format(subtotal));
System.out.println("Tax: " + "$" + decimalFormat.format(tax));
System.out.println("Total: " + "$" + decimalFormat.format(total));
System.out.println("Tendered: " + "$" + decimalFormat.format(tendered));
System.out.println("Change: " + "$" + moneyString);
System.out.println(twenties + " Twenties");
System.out.println(tens + " Tens");
System.out.println(fives + " Fives");
System.out.println(ones + " Ones");
System.out.println(quarters + " Quarters");
System.out.println(dimes + " Dimes");
System.out.println(nickels + " Nickels");
System.out.println(pennies + " Pennies");
}
}
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class ChangeTenderedWorking {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the purchase price: ");
BigDecimal price = scan.nextBigDecimal();
System.out.println("Enter the amount paid: ");
BigDecimal amountPayed = scan.nextBigDecimal();
Map<Denomination, Integer> changeDue = getDenomination(amountPayed, price);
for(Denomination denomination : changeDue.keySet()) {
System.out.println("Return " + denomination + " bill(s) : "+ changeDue.get(denomination));
}
scan.close();
}
public static Map<Denomination, Integer> getDenomination(BigDecimal amountPayed, BigDecimal price) {
BigDecimal change = amountPayed.subtract(price);
System.out.println("Return change -- "+ change);
Map<Denomination, Integer> changeReturn = new LinkedHashMap<Denomination, Integer>();
for(Denomination denomination : Denomination.values()) {
BigDecimal[] values = change.divideAndRemainder(denomination.value, MathContext.DECIMAL32);
if(!values[0].equals(BigDecimal.valueOf(0.0)) && !values[1].equals(BigDecimal.valueOf(0.0))) {
changeReturn.put(denomination, values[0].intValue());
change = values [1];
}
}
return changeReturn;
}
enum Denomination {
HUNDRED(BigDecimal.valueOf(100)),
FIFTY(BigDecimal.valueOf(50)),
TWENTY(BigDecimal.valueOf(20)),
TEN(BigDecimal.valueOf(10)),
FIVE(BigDecimal.valueOf(5)),
TWO(BigDecimal.valueOf(2)),
ONE(BigDecimal.valueOf(1)),
QUARTER(BigDecimal.valueOf(0.25)),
DIME(BigDecimal.valueOf(0.10)),
NICKEL(BigDecimal.valueOf(0.5)),
PENNY(BigDecimal.valueOf(0.1));
private BigDecimal value;
Denomination(BigDecimal value) {
this.value = value;
}
}
}
Related
I am a bit confused, I have a little program I wrote for a school assignment, the constraints I am required to work with is that no method can contain more than 15 lines of code, and we cannot use any for next loops.
What I cant seem to figure out is why I am able to pass an integer to my rounding method and it even returns the rounded value, but then it jumps back to my if / then statements (which it shouldnt be doing) and does not pass the variable.
It is a very rudimentary program I know...my coding skills are not very good, but any help would be appreciated.
The variables I need passed back are testscore and GPA, those need to go back to the main method so they can be stored to new variables and finally pushed off into the results method.
Im still pretty new to coding and the community and how things work...
import java.util.*;
public class Admit {
public static void main(String[] Args) {
Scanner console = new Scanner(System.in);
Introduction();
double testscore = 0;
double GPA = 0;
int Student = 1;
ACTSATScores(1,0,console);
double StudentOneTestScore = testscore;
GPAInfo(0,console);
double StudentOneGPAScore = GPA;
Student = 2;
ACTSATScores(2,0,console);
double StudentTwoTestScore = testscore;
GPAInfo(0,console);
double StudentTwoGPAScore = GPA;
DisplayResults(StudentOneTestScore,StudentOneGPAScore,StudentTwoTestScore,StudentTwoGPAScore);
}
public static void Introduction() {
System.out.println("This program compares two applicants to");
System.out.println("determine which one seems like the stronger");
System.out.println("applicant. For each candidate I will need");
System.out.println("either SAT or ACT scores plus a weighted GPA.");
System.out.println();
}
public static double ACTSATScores(int Student,double testscore,Scanner console) {
System.out.println("Information for applicant #" + Student + ":");
System.out.print("do you have 1) SAT scores or 2) ACT scores? ");
int ACTSAT = console.nextInt();
if ( ACTSAT == 1) {
SAT(Student,testscore,console);
}
if ( ACTSAT == 2) {
ACT(Student,testscore,console);
}
return testscore;
}
public static double SAT(int Student,double testscore,Scanner console) {
System.out.print("SAT math? ");
int SATMath = console.nextInt();
System.out.print("SAT critical reading? ");
int SATReading = console.nextInt();
System.out.print("SAT writing? ");
int SATWriting = console.nextInt();
testscore = ( ( 2 * SATMath + SATReading + SATWriting ) / 32);
System.out.println("exam score = " + roundNumber(testscore));
return ( ( 2 * SATMath + SATReading + SATWriting ) / 32);
}
public static double ACT(int Student,double testscore,Scanner console) {
System.out.print("ACT English? ");
int ACTEnglish = console.nextInt();
System.out.print("ACT math? ");
int ACTMath = console.nextInt();
System.out.print("ACT reading? ");
int ACTReading = console.nextInt();
System.out.print("ACT science? ");
int ACTScience = console.nextInt();
testscore = ( ( 2 * ACTMath + ACTEnglish + ACTReading + ACTScience ) / 1.8 );
System.out.println("exam score = " + roundNumber(testscore));
return testscore;
}
public static double GPAInfo(double GPA,Scanner console) {
System.out.print("overall GPA? ");
double OverallGPA = console.nextDouble();
System.out.print("max GPA? ");
double MaxGPA = console.nextDouble();
System.out.print("Transcript Multiplier? ");
double TranscriptMultiplier = console.nextDouble();
GPA = ( OverallGPA / MaxGPA * 100 * TranscriptMultiplier );
System.out.println("GPA score = " + roundNumber(GPA));
return GPA;
}
public static double roundNumber(double number) {
return (Math.round(number * 10)) / 10.0;
}
public static double DisplayResults(double StudentOneTestScore, double StudentOneGPAScore, double StudentTwoTestScore, double StudentTwoGPAScore) {
System.out.println("First applicant overall score = " + StudentOneTestScore + StudentOneGPAScore);
System.out.println("Second applicant overall score = " + StudentTwoTestScore + StudentTwoGPAScore);
if ( StudentOneTestScore + StudentOneGPAScore > StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The first applicant seems to be better");
}
else if ( StudentOneTestScore + StudentOneGPAScore < StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The second applicant seems to be better");
}
else {
System.out.println("The two applicants seem to be equal");
}
return StudentOneTestScore;
}
}
Expected output:
This program compares two applicants to
determine which one seems like the stronger
applicant. For each candidate I will need
either SAT or ACT scores plus a weighted GPA.
Information for applicant #1:
do you have 1) SAT scores or 2) ACT scores? 1
SAT math? 450
SAT critical reading? 530
SAT writing? 490
exam score = 60.0
overall GPA? 3.4
max GPA? 4.0
Transcript Multiplier? 0.9
GPA score = 76.5
Information for applicant #2:
do you have 1) SAT scores or 2) ACT scores? 2
ACT English? 25
ACT math? 20
ACT reading? 18
ACT science? 15
exam score = 54.4
overall GPA? 3.3
max GPA? 4.0
Transcript Multiplier? 0.95
GPA score = 78.4
First applicant overall score = 136.5
Second applicant overall score = 132.8
The first applicant seems to be better
My output
This program compares two applicants to
determine which one seems like the stronger
applicant. For each candidate I will need
either SAT or ACT scores plus a weighted GPA.
Information for applicant #1:
do you have 1) SAT scores or 2) ACT scores? 1
SAT math? 450
SAT critical reading? 530
SAT writing? 490
exam score = 60.0
overall GPA? 3.4
max GPA? 4.0
Transcript Multiplier? 0.9
GPA score = 76.5
Information for applicant #2:
do you have 1) SAT scores or 2) ACT scores? 2
ACT English? 25
ACT math? 20
ACT reading? 18
ACT science? 15
exam score = 54.4
overall GPA? 3.3
max GPA? 4.0
Transcript Multiplier? 0.95
GPA score = 78.4
First applicant overall score = 0.00.0
Second applicant overall score = 0.00.0
The two applicants seem to be equal
Corrected Code for anyone that needs it
import java.util.*;
public class Admit {
public static void main(String[] Args) {
Scanner console = new Scanner(System.in);
Introduction();
int Student = 1;
double StudentOneTestScore = ACTSATScores(1,console);
double StudentOneGPAScore = GPAInfo(0,console);
Student = 2;
double StudentTwoTestScore = ACTSATScores(1,console);
double StudentTwoGPAScore = GPAInfo(0,console);
DisplayResults(StudentOneTestScore,StudentOneGPAScore,StudentTwoTestScore,StudentTwoGPAScore);
}
public static void Introduction() {
System.out.println("This program compares two applicants to");
System.out.println("determine which one seems like the stronger");
System.out.println("applicant. For each candidate I will need");
System.out.println("either SAT or ACT scores plus a weighted GPA.");
System.out.println();
}
public static double ACTSATScores(int Student,Scanner console) {
double testscore = 0;
System.out.println("Information for applicant #" + Student + ":");
System.out.print(" do you have 1) SAT scores or 2) ACT scores? ");
int ACTSAT = console.nextInt();
if ( ACTSAT == 1) {
testscore = SAT(console);
}
if ( ACTSAT == 2) {
testscore = ACT(console);
}
return testscore;
}
public static double SAT(Scanner console) {
System.out.print(" SAT math? ");
int SATMath = console.nextInt();
System.out.print(" SAT critical reading? ");
int SATReading = console.nextInt();
System.out.print(" SAT writing? ");
int SATWriting = console.nextInt();
double testscore = ( ( 2 * SATMath + SATReading + SATWriting ) / 32);
System.out.println(" exam score = " + roundNumber(testscore));
return testscore;
}
public static double ACT(Scanner console) {
System.out.print(" ACT English? ");
int ACTEnglish = console.nextInt();
System.out.print(" ACT math? ");
int ACTMath = console.nextInt();
System.out.print(" ACT reading? ");
int ACTReading = console.nextInt();
System.out.print(" ACT science? ");
int ACTScience = console.nextInt();
double testscore = ( ( 2 * ACTMath + ACTEnglish + ACTReading + ACTScience ) / 1.8 );
System.out.println(" exam score = " + roundNumber(testscore));
return testscore;
}
public static double GPAInfo(double GPA,Scanner console) {
System.out.print(" overall GPA? ");
double OverallGPA = console.nextDouble();
System.out.print(" max GPA? ");
double MaxGPA = console.nextDouble();
System.out.print(" Transcript Multiplier? ");
double TranscriptMultiplier = console.nextDouble();
GPA = ( OverallGPA / MaxGPA * 100 * TranscriptMultiplier );
System.out.println(" GPA score = " + roundNumber(GPA));
System.out.println();
return GPA;
}
public static double roundNumber(double number) {
return (Math.round(number * 10)) / 10.0;
}
public static double finalScore(double TestScore, double GPAScore) {
return TestScore + GPAScore;
}
public static double DisplayResults(double StudentOneTestScore, double StudentOneGPAScore, double StudentTwoTestScore, double StudentTwoGPAScore) {
double StudentOneScore = finalScore(StudentOneTestScore,StudentOneGPAScore);
double StudentTwoScore = finalScore(StudentTwoTestScore,StudentTwoGPAScore);
System.out.println("First applicant overall score = " + roundNumber(StudentOneScore)); //StudentOneTestScore + StudentOneGPAScore);
System.out.println("Second applicant overall score = " + roundNumber(StudentTwoScore)); //StudentTwoTestScore + StudentTwoGPAScore);
if ( StudentOneTestScore + StudentOneGPAScore > StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The first applicant seems to be better");
} else if ( StudentOneTestScore + StudentOneGPAScore < StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The second applicant seems to be better");
} else {
System.out.println("The two applicants seem to be equal");
}
return StudentOneTestScore;
}
}
It seems you have a problem when using methods, returning types and inmutable types.
In the main section:
double testscore = 0;
double GPA = 0;
int Student = 1;
ACTSATScores(1,0,console);
double StudentOneTestScore = testscore;
GPAInfo(0,console);
double StudentOneGPAScore = GPA;
Student = 2;
ACTSATScores(2,0,console);
double StudentTwoTestScore = testscore;
You are assigning those variables the value "testscore". But you really never change that value, and the way you wrote the methods makes me believe that you are expecting testscore to change inside the methods.
Try printing the value of testscore in the main to see that it does not change its value (it should be always 0 in that main). This might be what you are looking for:
double StudentOneTestScore = ACTSATScores(1,0,console);
Why do I keep getting the error
symbol not found
for hamburger, cheeseburger, etc.? I also am getting an error for the * sign. I used a template to create this program. I don't understand why it is not compiling.
import java.util.Scanner;
import java.text.NumberFormat;
public class Assignment2
{
public static void main (String[] args)
{
final (double) HAMBURGER_COST = 2.75;
final (double) CHEESBURGER_COST = 3.25;
final (double) FRENCHFRIES_COST = 2.50;
final (double) BEVERAGE_COST = 1.50;
String hamburger, cheeseburger, fries, beverages;
Scanner in = new Scanner(System.in);//allows user input
System.out.println("Welcome to the In-N-Out Burger menu:");
System.out.println("______________________________________");
System.out.println("Hamburger $2.75");
System.out.println("Cheeseburger $3.25");
System.out.println("French Fries $2.50");
System.out.println("Shake & Beverage $1.50");
System.out.print("How many hamburger(s) would you like to buy?");
hamburgers = scan.nextInt();
System.out.print("How many cheeseburger(s) would you like to buy?");
cheeseburgers = scan.nextInt();
System.out.print("How many French fries would you like to buy?");
fries = scan.nextInt();
System.out.print("How many drinks would you like to buy?");
beverages = scan.nextInt();
double hamburgerCost = (double)HAMBURGER_COST * hamburger;
double cheesebugerCost = (double)CHEESBURGER_COST * cheeseburger;
double frenchfriesCost = (double)FRENCHFRIES_COST * fries;
double beverageCost = (double)BEVERAGE_COST * beverages;
double orderCost = (double)hamburgerCost + (double)cheesebugerCost +
(double)frenchfriesCost + (double)beverageCost;
int numberItems = Hamburgers + Cheesburgers + Fries + Beverages;
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
System.out.println("Hamburger Cost : " + fmt1.format(hamburgerCost));
System.out.println("Cheeseburger Cost : " + fmt1.format(cheesebugerCost));
System.out.println("French Fries Cost : " + fmt1.format(frenchfriesCost));
System.out.println("Order Cost : " + fmt1.format(beverageCost));
System.out.println("Shake & Beverage Cost : " + fmt1.format(beverageCost));
System.out.println("Total number of items ordered : " + numberItems);
}
}
There are two things I need assistance with. One is a problem with the rounding in the output and the other is just to find a better way to write my program that outputs the same results, if necessary.
What is the most efficient way to write this program? Even though it works like it should, I know it is not designed the best.
package program2;
import java.util.*;
class PiggyBank
{
Scanner console = new Scanner( System.in );
private int numPennies, numNickles, numDimes, numQuarters;
private float total;
public PiggyBank( int pennies, int nickles, int dimes, int quarters )
{
numPennies = pennies;
numNickles = nickles;
numDimes = dimes;
numQuarters = quarters;
total = (float) 0.00;
}
public void addPennies( int pennies )
{
System.out.println( "Have entered " + pennies + " pennies" );
if ( pennies < 0 )
{
System.out.println( "No Pennies Added" );
}
else
{
numPennies = numPennies + pennies;
total = (float) ( total + pennies * 0.01 );
}
}
public void addNickles( int nickles )
{
System.out.println( "Have entered " + nickles + " nickles" );
if ( nickles < 0 )
{
System.out.println( "No Nickles Added" );
}
else
{
numNickles = numNickles + nickles;
total = (float) ( total + nickles * 0.05 );
}
System.out.println( "Bank has $" + total + " in it" );
System.out.println();
}
public void addDimes( int dimes )
{
System.out.println( "Have entered " + dimes + " dimes" );
if ( dimes < 0 )
{
System.out.println( "No Dimes Added" );
}
else
{
numDimes = numDimes + dimes;
total = (float) ( total + dimes * 0.10 );
}
System.out.println( "Bank has $" + total + " in it" );
System.out.println();
}
public void addQuarters( int quarters )
{
System.out.println( "Have entered " + quarters + " quarters" );
if ( quarters < 0 )
{
System.out.println( "No Quarters Added" );
}
else
{
numQuarters = numQuarters + quarters;
total = (float) ( total + quarters * 0.25 );
}
}
public float getContents()
{
return total;
}
public final int breakTheBank()
{
if ( total >= 0 )
{
total = 0;
}
return (int) total;
}
}
public class PiggyBankTester
{
public static void main( String[] args )
{
Scanner console = new Scanner( System.in );
System.out.print( "Program By " );
String name = console.next();
System.out.println();
test();
}
public static void test()
{
PiggyBank bank = new PiggyBank( 0, 0, 0, 0 );
bank.addNickles( 3 );
bank.addPennies( 4 );
System.out.println( "Bank has $" + bank.getContents() + " in it \n" );
bank.addPennies( -18 );
System.out.println( "Bank has $" + bank.getContents() + " in it \n" );
bank.addDimes( 2 );
bank.addQuarters( 3 );
System.out.println( "Bank has $" + bank.getContents() + " in it \n" );
bank.addQuarters( -3 );
System.out.println( "Bank has $" + bank.getContents() + " in it \n" );
System.out.println( "Broke the bank and got $" + bank.getContents() + " from it \nBank has $" + bank.breakTheBank() + " in it" );
}
}
Here is a sample of my output. The float total rounded some of the results but I am not sure how to get it to round all of the results.
Program By JakeBrono46
Have entered 3 nickles
Bank has $0.15 in it
Have entered 4 pennies
Bank has $0.19000001 in it
Have entered -18 pennies
No Pennies Added
Bank has $0.19000001 in it
Have entered 2 dimes
Bank has $0.39000002 in it
Have entered 3 quarters
Bank has $1.14 in it
Have entered -3 quarters
No Quarters Added
Bank has $1.14 in it
Broke the bank and got $1.14 from it
Bank has $0 in it
I did use another site to find the structures for the accessors and mutators. I do not think I am missing anything too major, but I just can't think of what else I need to do at the moment.
find a better way to write my program that outputs the same results
import java.util.*;
import java.text;
class PiggyBank
{
Scanner console = new Scanner(System.in);
NumberFormat formatter = NumberFormat.getCurrencyInstance();
private int numPennies, numNickles, numDimes, numQuarters;
private float total;
public PiggyBank(int pennies, int nickles, int dimes, int quarters)
{
numPennies = pennies;
numNickles = nickles;
numDimes = dimes;
numQuarters = quarters;
total = 0.00;
}
I would use the NumberFormat class in the Text package. This way you can format numbers to your default currency (In this case dollars). You also do not need to cast float to your total variable since you declared it as a float instance variable.
bank.addPennies(4);
System.out.println("Bank has" + formatter.format(bank.getContents()) + " in it \n");
You use the formatter like so to print the formatted $#.## which allows you to avoid explicitly adding a dollar sign.
public final int breakTheBank()`
{
if(total >= 0)
{
total = 0;
}
return (int) total;
}
I would just change the if statement to if(total == 0) because you don't need to check if it's 0 if your going to change it to 0 anyway. Other than that there are not many changes that you can make.
One is a problem with the rounding in the output
Here is a method that I tend to use when rounding decimal numbers, so when you output a total just call it. More information can be found here about rounding numbers:
Round a double to 2 decimal places
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
find a better way to write my program that outputs the same results
If I was tasked to do this I would have used enumerations, where you can just create a enum value for every coin. If you're unsure on how to use enumerations take a look here for more information, https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
What you'd want to do in your case is to create a enum called Coins, where is takes a float of the value of that coin. Then create another method for instance addCoin where that would take a enum of coin and the amount to be added. Then simply calculate the result by accessing the value of the coin in the enum and multiplying it by the amount that's added.
The below code is not calculating the best way to distribute change in a Java 'cash register'. How do I fix it?
public void generateUSDChange(){
change = payment-purchase;
quarters = (int) (change/.25);
change -= (quarters * .25);
dimes = (int) (change/.1);
change -= (dimes * .1);
nickels = (int) (change/.05);
change -= (nickels * .05);
pennies = (int) (change/.01);
changeamount = quarters*.25 + dimes*.1 + nickels*.05 + pennies*.01;
if(changeamount != (payment-purchase)){
pennies++;
if(pennies>=5){
nickels++;
pennies-=5;
}
if(nickels>=2){
dimes++;
nickels-=2;
}
if(((dimes*.1) + (nickels*.05)) >= .25){
quarters++;
dimes-=2;
nickels--;
}
}
}
As others also suggested double and floats are not good for currency. You can use BigDecimal. Here's the working code:
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;
public enum CurrencyDenomination {
HUNDRED(BigDecimal.valueOf(100)), FIFTY(BigDecimal.valueOf(50)), TWENTY(BigDecimal.valueOf(20)),
TEN(BigDecimal.valueOf(10)), FIVE(BigDecimal.valueOf(5)), ONE(BigDecimal.valueOf(1)),
QUARTER(BigDecimal.valueOf(.25)), DIME(BigDecimal.valueOf(.10)),
NICLE(BigDecimal.valueOf(.05)), PENNIES(BigDecimal.valueOf(.01));
private BigDecimal value;
CurrencyDenomination(BigDecimal value) {
this.value = value;
}
public static Map<CurrencyDenomination, Integer> calculate(BigDecimal balance) {
Map<CurrencyDenomination, Integer> balanceCurrency = new LinkedHashMap<CurrencyDenomination, Integer>();
BigDecimal leftOver = balance;
System.out.println("Given amount : "+balance);
for (CurrencyDenomination currencyDenomination : CurrencyDenomination
.values()) {
int count = leftOver.divide(currencyDenomination.value).intValue();
if (leftOver != BigDecimal.ZERO) {
if (balanceCurrency.containsKey(currencyDenomination)) {
int existingCount = balanceCurrency
.get(currencyDenomination);
existingCount = existingCount + count;
balanceCurrency.put(currencyDenomination, existingCount);
} else {
balanceCurrency.put(currencyDenomination, count);
}
}
leftOver = leftOver.remainder(currencyDenomination.value);
if (leftOver.equals(BigDecimal.ZERO)) {
break;
}
}
return balanceCurrency;
}
public static void main(String[] args) {
System.out.println("BalanceCurrency : "+calculate(BigDecimal.valueOf(49.52)));
}
}
Output:
Given amount : 49.52
BalanceCurrency : {HUNDRED=0, FIFTY=0, TWENTY=2, TEN=0, FIVE=1, ONE=4, QUARTER=2, DIME=0, NICLE=0, PENNIES=2}
I agree with the above answer and comment about using BigDecimal. Another way to handle it would be to use integer values that represent cents, assuming you are using USD currency. You could try something like this. (The currency amounts are just examples for easy testing)
public void generateUSDChange(){
int payment = 500; //$5.00
int purchase = 268; //$2.68
int change = payment - purchase;
int quarters = change / 25;
change = change % 25;
int dimes = change / 10;
change = change % 10;
int nickles = change / 5;
int pennies = change % 5;
System.out.println("Your change is " + quarters + " quarters " + dimes + " dimes " + nickles + " nickles, and "+ pennies + " pennies.");
int change = pennies * 1 + nickles * 5 + dimes * 10 + quarters * 25;
System.out.printf("Your change totals to $%d.%02d", change/100, change%100);}
I am practicing out of a book, self study.
It is blowing my mind. If someone could help me ?
How do I subtract the amount of the first, second and third bag as well as collect the total
number of bag?
The project asks these criteria >
Assignment details
The company sells coffee only in 2 pound bags.
The price for each bags is 5.50.
When a customer places an order, they are shipped the coffee in boxe.
The boxes come in three sizes. Large(Contains 20 bags, medium(contains 10 bags, and small(contains 5 bags).
The cost of a large box is $1.80
medium $1.00
small $0.60
The order is shipped in the least expensive manner, for examples.
the fule for packing is to fill the large and medium boxes completely. that is, the box is fuly packed. Only the small boxes can have empty spaces. but that would not leave the third box fully packed. Develop a program that computes the total cost of an order. Display the following format:
Number of bags ordered: 52 - $ 286.00
Boxes used
2 Large - 3.60
1 medium - 1.00
1 small - 0.60
Your total cost is: $291.20
sample code
import javax.swing.*;
import java.lang.*;
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
import java.math.*;
public class CoffeeBags {
public static void main(String [] args) throws IOException
{
DecimalFormat df = new DecimalFormat ("#,##0.00");
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
int numberOfBags;
int largeBags = 2;
int mediumBags = 1;
int smallBags = 1;
double costOfLargeBags = 3.60;
double costOfMediumBags = 1.00;
double costOfSmallBags = 0.60;
double costPerBag = 5.50;
double totalCost;
double totalCostWithBags;
System.out.print("Enter number of bags to order: ");
String numberOfBagsStr = bufReader.readLine();
numberOfBags = Integer.parseInt(numberOfBagsStr);
totalCost = numberOfBags * costPerBag;
System.out.println("Number of bags ordered: " + numberOfBags + " - $" + df.format(totalCost));
System.out.println("Boxes used:");
System.out.println(" " + largeBags + " Large - $" + df.format(costOfLargeBags));
System.out.println(" " + mediumBags + " Medium - $" + df.format(costOfMediumBags));
System.out.println(" " + smallBags + " Small - $" + df.format(costOfSmallBags));
//System.out.print("Your total cost is: $ " + (totalCostWithBags));
//String numberOfUnitsStr = bufReader.readLine();
//numberOfUnits = Integer.parseInt(numberOfUnitsStr);
System.out.println("\nPress any key to continue. . .");
System.exit(0);
}
}
You're misunderstanding the exercise, based on your variable names. You have -boxes- which can fit 20/10/5 bags, depending on the size; large and medium boxes must be full, small ones do not need to be.
So you take the whole number of bags, divide by 20, put that many in large boxes; then take the remainder, divide by 10, then the remainder of that goes into small boxes.
Look here for operators; dividing an int by another int will always round down.
I came up with the following code that achieves your goal. Using ints to round down is very useful in this situation. You also need to name your variables correctly. They are bags going into boxes, not bags going into bags.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
public class CoffeeBags {
public static void main(String [] args) throws IOException {
DecimalFormat df = new DecimalFormat ("#,##0.00");
BufferedReader bufReader = new BufferedReader(
new InputStreamReader(System.in));
int numberOfBags = 0;
int numberOfBoxes = 0;
int numberLargeBoxes = 0;
int numberMediumBoxes = 0;
int numberSmallBoxes = 0;
double costOfLargeBox = 1.80;
double costOfMediumBox = 1.00;
double costOfSmallBox = 0.60;
double totalCostLargeBoxes;
double totalCostMediumBoxes;
double totalCostSmallBoxes;
double totalBoxCost;
double costPerBag = 5.50;
double totalBagCost;
double totalCostWithBags;
System.out.print("Enter number of bags to order: ");
String numberOfBagsStr = bufReader.readLine();
try {
numberOfBags = Integer.parseInt(numberOfBagsStr);
} catch (NumberFormatException e) {
System.out.println("Error: Enter digits only");
}
totalBagCost = numberOfBags * costPerBag;
if (numberOfBags > 20) {
numberLargeBoxes = numberOfBags/20;
}
if (numberOfBags - (numberLargeBoxes*20) < 20 || numberLargeBoxes == 0) {
numberMediumBoxes = (numberOfBags - (numberLargeBoxes*20))/10;
}
if (numberOfBags - (numberLargeBoxes*20) - (numberMediumBoxes*10) < 10 ||
numberLargeBoxes == 0 || numberMediumBoxes == 0) {
numberSmallBoxes = (numberOfBags - (numberLargeBoxes*20) - (numberMediumBoxes*10))/5;
}
if (numberOfBags - (numberLargeBoxes*20) - (numberMediumBoxes*10) -
(numberSmallBoxes*5) < 5 && numberOfBags - (numberLargeBoxes*20) - (numberMediumBoxes*10) -
(numberSmallBoxes*5) > 0 || numberLargeBoxes == 0 || numberMediumBoxes == 0) {
numberSmallBoxes++;
}
totalCostLargeBoxes = numberLargeBoxes*costOfLargeBox;
totalCostMediumBoxes = numberMediumBoxes*costOfMediumBox;
totalCostSmallBoxes = numberSmallBoxes*costOfSmallBox;
totalBoxCost = totalCostLargeBoxes + totalCostMediumBoxes + totalCostSmallBoxes;
totalCostWithBags = totalBoxCost + totalBagCost;
System.out.println("Number of bags ordered: " + numberOfBags + " - $" + df.format(totalBagCost));
System.out.println("Boxes used: ");
System.out.println(" " + numberLargeBoxes + " Large - $" + df.format(totalCostLargeBoxes));
System.out.println(" " + numberMediumBoxes + " Medium - $" + df.format(totalCostMediumBoxes));
System.out.println(" " + numberSmallBoxes + " Small - $" + df.format(totalCostSmallBoxes));
System.out.println("Your total cost is: $ " + df.format(totalCostWithBags));
}
}