Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Not returning when using decimals

$
0
0
Hey, everyone, I've got a little problem involving a program that returns the change a person gets after specifying a price, and how much money they paid for the item with.

The problem only occurs however, when the amount paid is a number such as 31.33, and the price is 20. I would expect it to return one 10, one 1, one .25, one .05, and three .01s. However, it just never responds. Is this because my cause is really repetitive? How could I make my program more efficient?

It does work fine if I enter 20 as the price, and 50 as the amount paid. Thanks for the help.

Here's my code

import java.util.ArrayList;
import java.util.Scanner;


public class ChangeCalculator {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);

		System.out.println("Please enter price: ");
		double price = input.nextDouble();

		System.out.print("Please enter amount paid: ");
		double paid = input.nextDouble();

		double change = paid - price;
		for (Double d : getChange(change)) {
			System.out.println(d);
		}

	}

	public static ArrayList<Double> getChange(double n) {
		ArrayList<Double> changeList = new ArrayList<Double>();
		while (n > 0) {

			while (n >= 100) {
				if (n < 100)
					break;
				changeList.add(100.0);
				n -= 100;
			}

			while (n >= 50) {
				if (n < 50)
					break;
				changeList.add(50.0);
				n -= 50;
			}

			while (n >= 20) {
				if (n < 20)
					break;
				changeList.add(20.0);
				n -= 20;
			}

			while (n >= 10) {
				if (n < 10)
					break;
				changeList.add(10.0);
				n -= 10;
			}

			while (n >= 5) {
				if (n < 5)
					break;
				changeList.add(5.0);
				n -= 5;
			}

			while (n >= 1) {
				if (n < 1)
					break;
				changeList.add(1.0);
				n -= 1;
			}

			while (n >= .25) {
				if (n < .25)
					break;
				changeList.add(0.25);
				n -= .25;
			}

			while (n >= .10) {
				if (n < .10)
					break;
				changeList.add(.10);
				n -= .10;
			}

			while (n >= .05) {
				if (n < .05)
					break;
				changeList.add(.05);
				n -= .05;
			}

			while (n >= .01) {
				if (n < .01)
					break;
				changeList.add(.01);
				n -= .01;
			}
		}
		return changeList;
	}

}


Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>