繁体   English   中英

数组索引超出界限异常:2

[英]Array Index Out Of Bounds Exception: 2

我说进入出口后我得到错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

我很喜欢编程所以请耐心等待

import java.util.*;

public class Highway{

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Total number of the exits");
        int p=input.nextInt();
        System.out.println("The first exit");
        int i=input.nextInt();
        System.out.println("The second exit");
        int j=input.nextInt();

        int[]A= new int[p];

        for(int w=0;w<=p;i++) {


            A[i]=(int )(java.lang.Math.random() * 20 + 1);
            System.out.println(A[w]);
        }
    }

    static void Distance(int i, int j, int[] A) {
    // a is the array of distance
    // this find the  distances between i and j
        int distance = 0;

        if(j>i){
        for(int k = i; k<=j;k++) {

                distance=distance+A[k];
        }

                distance=distance-A[i];

        }

        if(i>j){
            for (int m = j; m<=i; m++){distance=distance+A[m];
            }
                distance=distance-A[j];
            }

            System.out.println("The distance of the first"+i+" and second exit"+j+" is"+distance);

        }
}

你的循环迭代到p包含,这就是你得到错误的地方! 数组的大小是p ,你应该迭代的索引是0,...,p-1加上你递增i而不是w

修改:

for(int w=0;w<=p;i++)

至:

for(int w=0;w<p;w++)

将for循环更改为以下内容

for(int w=0;w<p;w++) {


        A[w]=(int )(java.lang.Math.random() * 20 + 1);
        System.out.println(A[w]);
    }

我在这里做的唯一更改是for条件,因为如果数组的大小是p,则可以在0,1,...,p-1访问数组值。 此外,您需要在for循环中增加w而不是i

此外,在数组中,您正在更新A[i]而不是A[w]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM