PiggyBank program with constructors, mutators, and accessors - java

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.

Related

How to list input values after the loop is done?

It is supposed calculate the sales commission based on input variables and list them after the loop is done.
I am unsure how to go about listing the values of totalEarned after because they change when the loop is done.
import java.util.Scanner;
public class SalesCommissionCalc
{
public static void main( String [] args )
{
final int SENTINEL = -1;
double grossSales;
double totalEarned;
Scanner scan = new Scanner( System.in );
System.out.print( "Enter gross sales for the last week, or -1 to stop > " );
grossSales = scan.nextDouble( );
while ( grossSales != SENTINEL )
{
totalEarned =(500 + (grossSales * .08));
System.out.println( "Earned last week: $" + totalEarned );
System.out.print( "Enter gross sales for the last week, or -1 to stop > " );
grossSales = scan.nextDouble( );
System.out.println( "Total Earned: $" + totalEarned );
}
}
}
Also if I added names to the program would I have to introduce another loop or would I be able to squeeze it into the same loop and keep the inputted names attached to the inputted values for when I list them after the loop?
You could save the values in a list and then retrieve and use them in the way you want to.
import java.util.Scanner;
public class SalesCommissionCalc
{
public static void main( String [] args )
{
final int SENTINEL = -1;
double grossSales;
double totalEarned;
//declare the list
List<double> earnings = new List<double>;
Scanner scan = new Scanner( System.in );
System.out.print( "Enter gross sales for the last week, or -1 to stop > " );
grossSales = scan.nextDouble( );
while ( grossSales != SENTINEL )
{
totalEarned =(500 + (grossSales * .08));
//add the value to the list
earnings.add(totalEarned);
System.out.println( "Earned last week: $" + totalEarned );
System.out.print( "Enter gross sales for the last week, or -1 to stop > " );
grossSales = scan.nextDouble( );
System.out.println( "Total Earned: $" + totalEarned );
}
//retrieve the value at the third position in the list
earnings.get(3); //here you could also use a foreach or for loop to iterate through all list entries
}
}
You must retrieve the values by passing them in a list or an array.
List<double> earned = new List<double>;

error: incompatible types: void cannot be converted to double [duplicate]

This question already has an answer here:
What does "Incompatible types: void cannot be converted to ..." mean?
(1 answer)
Closed 6 years ago.
import java.util.*;
// This program will estimate the cost to paint a room in your house
public class PaintJobEstimator {
// square feet per one gallon of paint.
public static final double AREA_PER_GALLON = 112.0;
// hours of labor needed to paint AREA_PER_GALLON square feet.
public static final double HOURS_PER_UNIT_AREA = 8.0;
// charge to customer for one hour of labor.
public static final double LABOR_COST_PER_HOUR = 35.0;
// main declares a Scanner that is passed to
// the input methods. main also controls the
// order of calculations.
public static void main( String[] args ) {
Scanner keyboard = new Scanner( System.in );
// How many square feet do we need to paint?
double sqft = getInput( keyboard,
"Enter the number of square feet: " );
// How much does a gallon of paint cost?
double gallonCost = getInput( keyboard,
"Enter the price of a gallon of paint: " );
////////////////////////////////////////
// Calculate the cost of this paint job.
////////////////////////////////////////
// First, how many gallons of paint do we need?
int numGallons = calculateGallons( sqft );
// How long will the job take?
double hoursLabor = calculateHours( sqft );
// How much will the paint cost?
double paintCost = calculatePaintCost( numGallons, gallonCost );
// How much will the labor cost?
double laborCost = calculateLaborCost( hoursLabor );
// What's the total bill?
double totalCost = calculateTotalCost( paintCost, laborCost );
// Print the results.
generateReport( sqft, gallonCost, numGallons, hoursLabor,
paintCost, laborCost, totalCost);
}
public static double getInput( Scanner input, String prompt ) {
System.out.print( prompt );
while ( !input.hasNextDouble() ) {
input.nextLine(); // get rid of bad input.
System.out.print( prompt );
}
double inValue = input.nextDouble();
input.nextLine(); // clear the input line.
return inValue;
}
// Your methods go here:
// calculateGallons
public static int calculateGallons( double sqft ) {
// TO DO return correct value
return (int)Math.ceil(sqft / AREA_PER_GALLON);
}
// calculateHours
public static double calculateHours( double sqft ) {
// TO DO return correct value
return sqft / 14;
}
// TO DO: calculatePaintCost
public static double calculatePaintCost (int numGallons, double gallonCost){
return numGallons * gallonCost;
}
// TO DO: calculateLaborCost (Hours * Labor/hr)
public static double calculateLaborCost( double hoursLabor ){
return hoursLabor * LABOR_COST_PER_HOUR;
}
// TO DO: calculateTotalCost
public static double calculateTotalCost( double paintCost, double laborCost ){
return paintCost + laborCost;
}
// To Do: generateReport
public static double generateReport(double sqft, double gallonCost, int numGallons, double hoursLabor, double paintCost, double laborCost, double totalCost) {
return System.out.print("To paint" + sqft + "square feet, with");
System.out.print("paint that costs" + gallonCost + "per gallon,");
System.out.print("you will need" + numGallons + "gallons of paint");
System.out.print("and" + hoursLabor + "hours of labor.");
System.out.print("The cost of the paint is: " + paintCost );
System.out.print("The cost of the labor is: "+ laborCost);
System.out.print("The total cost of the job is: " + totalCost);
System.out.println();
}
}
I am having with the generateReport method, i don't know how to return it properly. i keep getting the error
PaintJobEstimator.java:99: error: incompatible types: void cannot be converted to double
return System.out.print("To paint" + sqft + "square feet, with");
^
what am i doing wrong. or am i just completely missing the point. I am new at this and really need help, i don't want to get the answer but if someone can point me in the right direction that would be great
System.out.print() returns no value; it has a return type of void.
In order to rewrite this without any errors, change it to something like this:
public static void generateReport(double sqft, double gallonCost, int numGallons, double hoursLabor, double paintCost, double laborCost, double totalCost) {
System.out.print("To paint" + sqft + "square feet, with");
System.out.print("paint that costs" + gallonCost + "per gallon,");
System.out.print("you will need" + numGallons + "gallons of paint");
System.out.print("and" + hoursLabor + "hours of labor.");
System.out.print("The cost of the paint is: " + paintCost );
System.out.print("The cost of the labor is: "+ laborCost);
System.out.print("The total cost of the job is: " + totalCost);
System.out.println();
System.out.print(...) prints given objects to output.
return is used to pass values to the caller of the function, in this case, your main method. Since your generateReport method is of type double, you have to return some double value. If you don't want to return anything, then your method should be void.
System.out.print(...) for instance, is a void function.

Cash Register Change Issue

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);}

Java class to break down change into coins?

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;
}
}
}

Java: Calculating Employee's Wage

I have again a problem regarding on how to display the calculated wage of the employee..
When I type in the hourly rate, the Gross Salary won't display..
Here's what I've done so far..
The WageCalcu.java
public class WageCalcu
{
private String employeeName;
private int hours;
private double rate, pay;
public void setEmployeeName ( String name )
{
employeeName = name;
}
public String getEmployeeName()
{
return employeeName;
}
public double calculatePay( int hours, double rate )
{
if ( hours > 40 )
{
int extraHours = hours - 40;
pay = ( 40 * rate ) + ( extraHours * rate );
}
else pay = hours * rate;
return pay;
}
public void displayEmployee()
{
System.out.printf( "Employee's name: %s", getEmployeeName() );
System.out.printf( "\nGross Salary: ", + pay );
}
}
The Employee.java
import java.util.Scanner;
public class Employee
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in);
WageCalcu employee = new WageCalcu();
System.out.print( "Enter Employee %s name: " );
String name = input.nextLine();
employee.setEmployeeName( name );
System.out.print( "Enter how many hours worked: " );
int hours = input.nextInt();
System.out.print( "Enter hourly rate: " );
double rate = input.nextInt();
employee.calculatePay( hours, rate );
employee.displayEmployee();
System.out.println();
}
}
I'm sure you meant:
System.out.printf( "\nGross Salary: %f", pay);
One more thing
double rate = input.nextInt();
Should be
double rate = input.nextDouble();
If you're really expecting a real number.
I would put: System.out.printf( "\nGross Salary: %.2f", pay); to show 2 decimals.
You have missed %s in printf( "\nGross Salary: ", + pay );
Five years late to this party, but I'll speak my piece.
You've set it up to determine how many overtime hours an employee has, but you're not calculating their overtime pay.
What you have:
pay = ( 40 * rate ) + ( extraHours * rate );
What it should be:
pay = ( 40 * rate ) + ( extraHours * rate * 1.5);

Categories

Resources