gpt4 book ai didi

java - 如何修复数组 OutOfBoundsException?

转载 作者:行者123 更新时间:2023-11-29 10:02:25 25 4
gpt4 key购买 nike

我正在为学校做一个项目,我们必须多次旋转一个立方体,并找到从立方体收到的数字的最长运行。我几乎完成了代码,它符合要求,但每当我运行它时,我都会遇到同样的错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at number_cube.number_cube.cubeToss(number_cube.java:20)
at number_cube.number_cube.main(number_cube.java:10)

谁能帮我解决这个问题?

这是我的代码:

public class number_cube { 
public static int ans;
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("How many times would you like to toss the cube?");
ans = scan.nextInt();
cubeToss();
getLongestRun();
System.out.println();
}

public static int arr[] = new int[ans];

public static int[] cubeToss(){
for(int i = 0; i < ans; i++){
int randnum = (int) (1 + Math.random() * (6-1));
arr[i] = randnum;
}
return arr;
}

public static void getLongestRun(){
int longest = 0;
int length = 1;
for(int i = 1; i < ans; i++)
if(arr[i] == arr[i-1]){
length++;
}

else{
length = 1;
}

if(length > longest){
longest = length;
}

System.out.println("The longest run is " + longest + ".");
}
}

最佳答案

您使用变量 ans 作为您的 arr 数组的长度,但是在创建数组时,ans 没有值(Java 将其初始化为 0),因此 arr 数组的长度为 0。main 方法在类初始化之前不会被调用;在调用 main 方法之前初始化所有 static 变量。

在获得有效长度之前不要创建数组:

ans = scan.nextInt();
arr = new int[ans]; // Add this line.
cubeToss();

关于java - 如何修复数组 OutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20225464/

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