Java 我的代码中存在ArrayIndexOutOfBoundsException错误

Java 我的代码中存在ArrayIndexOutOfBoundsException错误,java,Java,在coins数组中找不到错误。当我尝试用n+10个元素初始化数组时,它成功了。但实际上它应该只使用n个元素。我哪里弄错了 import java.util.Scanner; public class MaximumContiguousSum { public static void main(String args[]){ Scanner in = new Scanner(System.in); int amou

在coins数组中找不到错误。当我尝试用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)
import java.util.Scanner;
公共类最大连续和{
公共静态void main(字符串参数[]){
扫描仪输入=新扫描仪(系统输入);
整数金额,n;
System.out.print(“输入硬币类型的数量:”);
n=in.nextInt();
整数[]硬币=新整数[n];
系统输出打印(“输入硬币值:”);
对于(inti=0;i

宣布硬币有n个元素,最大索引为n-1

这个


while(coins[j]您有一个off by one错误。您的线路:

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

while(硬币[j]不要在错误行上检查大于或等于


更改此
while(coins[j]哪一行是第22行?如所示:
MaximumContiguousSum.java:22
while(coins[j]如果
j
等于
n
,则数组
coins
的索引超出范围。将
j
放在
coins[j]之前你的程序打算做什么?预期的输出是什么?这是一个dp问题“进行更改”输出应该是3。我已经尝试了“while(coins[j]不适合jit检查j=2和I=2 bcoz有条件coins[j]是的,关于这一点你是对的。我将把它留到上下文中,但当j==n时它也起作用,所以当你在coins[j]中使用它时,你最终会得到数组越界错误。
while(coins[j]<=i && j<=n){
   arr[i]=min(arr[i], 1+arr[i-coins[j]]);
while(coins[j]<=i && j<n)
while(j < n && coins[j]<=i)
while(coins[j]<=i && j<=n)