-2

I just started coding in java and I am working on a change machine-esk program. I know It can be condensed but Its part of the constraints. It keeps out putting random change owed and quarter count...

import java.util.Scanner;
public class Change {

    public static void main(String[] args) {
        double costVar, paidVar, amountOwed;//user defined

        //defining the vale of US coins 
        final double quarterCoin = 0.25;
        final double dimeCoin = 0.10;
        final double nickelCoin = 0.05;
        final double pennyCoin = 0.01;

        //Variable for math stuff
        double quarterAmountdec, dimeAmountdec, nickelAmountdec, pennyAmountdec;
        short quarterAmountfin, dimeAmountfin, nickelAmountfin, pennyAmountfin;

        Scanner keyboard = new Scanner(System.in);

        //ask the user to input costs and amount payed (assuming the amount paid is > or = the cost of the item)
        System.out.println("Enter Item Cost: ");
        costVar=keyboard.nextDouble();
        System.out.println("Enter Amount Paid: ");
        paidVar=keyboard.nextDouble();

        amountOwed = paidVar - costVar;//math for the changed owed
        System.out.println("\nChange Owed: $" +amountOwed++);//displaying how much change the machine owes

        //math to calculate the coins owed (involves intentional loss of accuracy

        quarterAmountdec = amountOwed / quarterCoin;
        quarterAmountfin = (short)quarterAmountdec;

        //outputs coins owed
        System.out.println("Quarters: " +quarterAmountfin++ );
    }

}

Output:

Enter Item Cost:
2.34
Enter Amount Paid:
6.89

Change Owed: $4.55
Quarters: 22

Tom
  • 16,842
  • 17
  • 45
  • 54
Drew G.
  • 3
  • 3

1 Answers1

1

The following line alters the amount owed after printing

        System.out.println("\nChange Owed: $" +amountOwed++);

Thus when printing the amount owed looks fine, but internally the value is changed. I am personally unsure of the behaviour of calling ++ on a double, however I recommend removing the ++ and re-running your code.

Sjoerd
  • 186
  • 1
  • 5
  • this helped but im still getting 0.888899999999 when I subtract 2.16 and 3.00 – Drew G. Oct 22 '15 at 12:21
  • 1
    This is because you use double, same would happen if you use float. The rounding can happen... here more details: http://stackoverflow.com/questions/322749/retain-precision-with-doubles-in-java Mike Jenkins mentioned this above. – Daniel Bişar Oct 22 '15 at 12:54
  • After learning abit more about coding; this make alot more sense. Thanks mate. – Drew G. Nov 24 '15 at 12:36