0

import java.io.*;

public class CoinChangeProblem {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    int[] arr;
    arr = new int[]{1, 2, 5, 10, 20, 50, 100, 500, 1000};
    int[] arr2;
    arr2 = new int[]{-1, -1, -1, -1, -1, -1, -1, -1, -1};
    int max_coin = 0, due, i = 0, j = 0;
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("\n\n\tEnter the amount of currency due");
    due = Integer.parseInt(stdin.readLine());
    while (due != 0) {
        for (j = 0; due > arr[j] && j < 9; )
            max_coin = arr[j++];
        j = 0;
        arr2[i] = max_coin;
        due = due - max_coin;
        i += 1;
    }
    i = 0;
    for (int k = 0; arr2[k] != -1; k++) {
        System.out.print(" " + arr2[k]);
    }
}
}

The compiler is throwing ArrayIndexOutOfBoundsException at line 9 and 23.If you have got a solution please help!

June7
  • 19,874
  • 8
  • 24
  • 34
learner
  • 3
  • 3

3 Answers3

0

Last iteration of your for loop makes arr2[i] = max_coin access arr2[9] but your array's last index is 8.

Bobzone
  • 276
  • 2
  • 12
  • Yeah I added a condition to restraint I up to 8 index and it is working fine,although logic has a hole itself,anyways thank you for ur kind help ☺ – learner Nov 09 '17 at 02:32
0

Change your loop as

for(j=0; j<9 && due>arr[j];)
    max_coin=arr[j++];

Java works with short circuiting, therefore when you check if j is smaller than 9 first, then it will be false and loop ends.

small_ticket
  • 1,910
  • 5
  • 22
  • 30
0

This program gets an input variable from standard input which is stored in 'due' local variable. It just works when the 'due' input is <= 7. If the input value is greater than 7 this exception raises:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at CoinChangeProblem.main(CoinChangeProblem.java:23)

Pay attention the '9' is not the line number, it indicates given index which is more than the max size of your array. The size of 'attr2' array is 9 and it supports [0-8] indexes. So when 'i' variable reaches to number 9, then 'arr2[i]' expressions causes the ArrayIndexOutOfBoundsException.

Kayvan Tehrani
  • 3,070
  • 2
  • 32
  • 46