gpt4 book ai didi

java - 数组索引越界异常: 2

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:42:47 24 4
gpt4 key购买 nike

当我进入导出后出现错误

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

关于java - 数组索引越界异常: 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32940456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com