javaarraysbank

How to check for a certain value and then exchange to money values in Java?


I was playing around with arrays and I wanted to create a program in which you enter the value of money and then check how many coins or bank notes you need to fill that value.

In case you enter 650 you should get one for: 500 one for 100 and one for 50. That's the program I got so far, but somehow it only prints out all of the values stored in bankovci array.

public static void main(String[] args) {

    int[]bills = {500,200,100,50,20,10,5,2,1};
    int amount=Integer.parseInt(JOptionPane.showInputDialog("Vnesi znesek: "));
    int sum=0;
    System.out.print("We will need bills for: ");
    while(sum<=amount)
    {
    for(int i=0; i < bills.length; i++)
    {
        if(amount-bills[i]>=0)
        {
            sum+=bills[i];

        }
        else if(amount-sum>bills[i])
        {
            i+=1;
        }System.out.print(bills[i]+", ");
    }


    }}}

Edit

In case I enter 650 or any other number I get the following output:

We will need bills for: 500, 200, 100, 50, 20, 10, 5, 2, 1,


Solution

  • There are cleaner ways of solving this problem (without using the break keyword), as I am sure other people will post. But to help you understand where you had trouble, here is a modified version of the code that you supplied. Notice that I changed the if statement, and removed the else block. I also had to add a break to exit the for loop early, which is what I think you were trying to use the i+1 for.

    public static void main(String[] args) {
        int[]bills = {500,200,100,50,20,10,5,2,1};
        int amount=250;
        int sum=0;
        System.out.print("We will need bills for: ");
        while(sum<amount)
        {
            for(int i=0; i < bills.length; i++)
            {
                if(sum+bills[i] <= amount)
                {
                    sum+=bills[i];
    
                    System.out.print(bills[i]+", ");
    
                    break;
                }
            }
        }}