Give change Learn programming with Java exercises

Lesson:

Flow Control


Exercise:

Give change 62


Objetive:

Create a java program to return the change of a purchase, using coins (or bills) as large as possible. Assume we have an unlimited amount of coins (or bills) of 100, 50, 20, 10, 5, 2 and 1, and there are no decimal places. Thus, the execution could be something like this:

Price? 44
Paid? 100
Your change is 56: 50 5 1
Price? 1
Paid? 100
Your change is 99: 50 20 20 5 2 2


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		int price, paid, change;

		System.out.print("Price? ");
		price = Integer.parseInt(new Scanner(System.in).nextLine());
		System.out.print("Paid? ");
		paid = Integer.parseInt(new Scanner(System.in).nextLine());

		change = paid - price;
		System.out.printf("Your change is %1$s: ", change);
		while (change > 0)
		{
			if (change >= 50)
			{
				System.out.print("50 ");
				change -= 50;
			}
			else
			{
				if (change >= 20)
				{
					System.out.print("20 ");
					change -= 20;
				}
				else
				{
					if (change >= 10)
					{
						System.out.print("10 ");
						change -= 10;
					}
					else
					{
						if (change >= 5)
						{
							System.out.print("5 ");
							change -= 5;
						}
						else
						{
							if (change >= 2)
							{
								System.out.print("2 ");
								change -= 2;
							}
							else
							{
								System.out.print("1 ");
								change -= 1;
							}
						}
					}
				}
			}
		}
		System.out.println();
	}
}