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!
Last iteration of your for loop makes arr2[i] = max_coin
access arr2[9]
but your array's last index is 8.