ArrayIndexOutOfBoundsException我的代码中出错

时间:2014-01-28 03:08:21

标签: java

无法在硬币数组中找到错误。当我试图用n + 10个元素初始化数组时,它起作用了。但实际上它应该只使用n个元素。我在哪里弄错了?

    import java.util.Scanner;

    public class MaximumContiguousSum {

        public static void main(String args[]){
            Scanner in = new Scanner(System.in);
            int amount, n; 
            System.out.print("Enter number of types of coins : ");
            n = in.nextInt();
            int[] coins = new int[n];
            System.out.print("Enter coins values : ");
            for(int i=0; i<n; i++){
                coins[i] = in.nextInt();
            }
            System.out.print("Enter the amount : ");
            amount = in.nextInt();
            int[] arr = new int[amount+1];
            arr[1]=1; arr[0]=0;
            for(int i=2; i<=amount; i++){
                arr[i]=100;
                int j=0;

//Error in the following line
                while(coins[j]<=i && j<n){
                    arr[i]=min(arr[i], 1+arr[i-coins[j]]);
                    j++;
                }
            }
            System.out.println("The number of coins to be used : " + arr[amount]);
            in.close();
        }

        private static int min(int a, int b) {
            // TODO Auto-generated method stub
            return (a<b)?a:b;
        }
    }


Output:

    Enter number of types of coins : 3
    Enter coins values : 1 2 7
    Enter the amount : 10
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
        at MaximumContiguousSum.main(MaximumContiguousSum.java:22)

3 个答案:

答案 0 :(得分:0)

int[] coins = new int[n];

声明硬币有n个元素,其最大索引为n - 1

while(coins[j]<=i && j<=n){
   arr[i]=min(arr[i], 1+arr[i-coins[j]]);

当j = n超过结束时,将尝试访问硬币[n]

编辑:arr [i-coins [j]]受到保护。

最后这个:

while(coins[j]<=i && j<n)

应该是这个

while(j < n && coins[j]<=i)

答案 1 :(得分:0)

您有一个错误的错误。你的行:

while(coins[j]<=i && j<=n)

在退出之前会尝试抓取硬币[n],并且阵列的最终索引实际上是n-1

答案 2 :(得分:0)

请勿在错误行上检查大于或等于

将此while(coins[j]<=i && j<n){更改为代码中的while(coins[j]<i && j<n){