Java: Adding Change to be Calculated too

user10149031 :

I am looking if anyone can help me figure out how to add to my code for it to also display the number of quarters, dimes, nickels, and pennies given the the number amount I input.

It is considered extra credit for my assignment, and I am curious to know how, but haven't found what I was looking for from similar questions like the one I am asking. Therefore, I'd appreciate if someone could help me out. (The dollar bill conversions work perfectly)

public static void main(String[] args) {

    double userInput = 0.0;
    int bills;

    Scanner inputScanner = new Scanner(System.in);

    System.out.println("Please enter the amount of money you would like: ");
    userInput = inputScanner.nextDouble();

    if (userInput < 0.0) {
        System.out.println("Goodbye!");
        inputScanner.close();
    }

    if (userInput > 0.0) {

        bills=(int)(userInput/20);
        System.out.println("You will receive:\n" + bills + " twenty dollar bills,");
        userInput=(userInput-(bills*20));
        bills=(int)(userInput/10);
        System.out.println(bills+" ten dollar bills,");
        userInput=(int)(userInput-(bills*10));
        bills=(int)(userInput/5);
        System.out.println(bills+" five dollar bills,");
        userInput=(userInput-(bills*5));
        bills=(int)(userInput/1);
        System.out.println(bills+" one dollar bills.");

    }

}
Sharon Ben Asher :

working with fractions of doubles can be tricky because of the aproximation that is done by the JVM. For example, the following code

double userInput = 123.39D;
double change = userInput - (int)userInput;  // suppose to be 0.39
System.out.println(change);

produces the output 0.39000000000000057

A workaround for this would be to multiply by 100 and assign to an int. this effectively "moves" the first two decimal digits to the left of the dot, where it is easy to do the math to get the required nominations:

public static final int QUARTER = 25;
public static final int DIME = 10;
public static final int NICKEL = 5;

    double userInput = 123.39D;
    double changeDouble = userInput - (int)userInput;  // get smaller-than-1-dollar change
    int changeInt = (int)(changeDouble * 100);  // move two digits from right to left of decimal dot
    System.out.println("quarters: " + changeInt / QUARTER);
    changeInt -= (changeInt / QUARTER) * QUARTER;
    System.out.println("dimes: " + changeInt / DIME);
    changeInt -= (changeInt / DIME) * DIME;
    System.out.println("nickels: " + changeInt / NICKEL);
    changeInt -= (changeInt / NICKEL) * NICKEL;
    System.out.println("pennies: " + changeInt);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159237&siteId=1