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

Change calculator going in an infinite loop

$
0
0
Well I've looked through the program and everything seems like it should work. What did I do wrong?

import java.util.Scanner;

public class QuizProgram1 {
	
    public static void main(String[] args) {
    	
    	System.out.print("How much money do you owe? (Please enter the ammount without a dollar sign like 33.89): ");
    	
    	Scanner in = new Scanner(System.in);
    	double amtOwed = in.nextDouble();
    	double amtRecv = 0.0;
    	double temp = amtOwed;
    	int twenty = 0, five = 0, one = 0, quarter = 0, dime = 0, nickel = 0, penny = 0;
    	
    	while (temp != 0.00) {
    		
    		if (temp >= 20.00) {
    			double t = ((int)temp / 20.00);
    			twenty += t;
    			temp -= t * 20.00;
    			amtRecv += t * 20.00;
    		} else if (temp >= 5.00) {
    			double t = ((int)temp / 5.00);
    			five += t;
    			temp -= t * 5.00;
    			amtRecv += t * 5.00;
    		} else if (temp >= 1.00) {
    			double t = ((int)temp / 1.00);
    			one += t;
    			temp -= t * 1.00;
    			amtRecv += t * 1.00;
    		} else if (temp >= 0.25) {
    			double t = (int) (temp / 0.25);
    			quarter += t;
    			temp -= t * 0.25;
    			amtRecv += t * 0.25;
    		} else if (temp >= 0.10) {
    			double t = (int) (temp / 0.10);
    			dime += t;
    			temp -= t * 0.10;
    			amtRecv += t * 0.10;
    		} else if (temp >= 0.05) {
    			double t = (int) (temp / 0.05);
    			nickel += t;
    			temp -= t * 0.05;
    			amtRecv += t * 0.05;
    		} else if (temp >= 0.01) {
    			double t = (int) (temp / 0.01);
    			penny += t;
    			temp -= t * 0.01;
    			amtRecv += t * 0.01;
    		}
    		
    	}
    	
    	
    	System.out.println("\nYou owe $" + amtRecv + "\nChange:\n");
    	
    	if (twenty > 0) {
    		System.out.println(twenty + " $20 bill(s)");
    	}
    	if (five > 0) {
    		System.out.println(five + " $5 bill(s)");
    	}
    	if (one > 0) {
    		System.out.println(one + " $1 bill(s)");
    	}
    	if (quarter > 0) {
    		System.out.println(quarter + " Quarter(s)");
    	}
    	if (dime > 0) {
    		System.out.println(twenty + " Dime(s)");
    	}
    	if (nickel > 0) {
    		System.out.println(nickel + " Nickel(s)");
    	}
    	if (penny > 0) {
    		System.out.println(penny + " Penny(ies)");
    	}
    	
    }
    
}



It only works if I enter an amount it can parse right away like 20.00, 40.00, 5.00, or 0.04. It goes in an infinite loop when I combine things like 15.97.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



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