简体   繁体   中英

Array Index Out Of Bounds Exception: 2

I get errors when after i enter the exits it says

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

Im terrible at programming so please bear with me

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);

        }
}

Your loop iterates until p inclusive, that's where you get the error! The size of the array is p and the indices you should iterate are 0,...,p-1 plus you're incrementing i instead of w .

Modify:

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

to:

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

Change your for loop to following

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


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

The only changes I have done here is in the for condition because if size of array is p then the array values can be accessed at 0,1,...,p-1. Also, you need to increment w instead of i in the for loop

Also, within the array you are updating A[i] instead of A[w]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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