[英]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.