简体   繁体   English

如何修复数组OutOfBoundsException?

[英]how to fix with array OutOfBoundsException?

I'm working on a project for school where we have to spin a cube a number of times and find the longest run of the numbers that are received from the cube. 我正在为一个学校项目工作,在该项目中,我们必须旋转多维数据集多次,并找到从多维数据集中收到的最长数字。 I am almost finished with the code, and it complies, but whenever I run it I get the same error: 我几乎完成了代码,并且代码符合要求,但是每当我运行它时,我都会遇到相同的错误:

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)

Can anybody help me with this? 有人可以帮我吗?

Here is my code: 这是我的代码:

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 + ".");
    }
}

You used the variable ans as the length of your arr array, but when the array was created, ans didn't have a value (Java initialized it to 0), so the arr array has length 0. The main method isn't called until the class is initialized; 您使用的变量ans作为您的长度arr数组,但在创建数组时, ans没有一个值(Java中初始化为0),所以arr数组长度为0, main方法是不叫直到类被初始化; all static variables are initialized before the main method is called. 在调用main方法之前,所有static变量均已初始化。

Don't create the array until you have a valid length: 长度有效之前,请勿创建数组:

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

You need to initialize the array after you got the value for ans. 你需要你得到了值后,以数组初始化for答。 Currently you are initialize the Array with ans = 0 at the startup for the program (where ans is 0). 当前,您在程序启动时使用ans = 0初始化Array(其中ans为0)。

A correct solution may be: 正确的解决方案可能是:

 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?");
        arr[] = new int[scan.nextInt()];
public static int arr[] = new int[ans];

From the jls-12.4: when The JVM is still trying to execute the method main of class number_cube , the invocation is permitted only if the class has been initialized. jls-12.4:当JVM仍在尝试执行number_cube类的main方法时,仅当该类已初始化时才允许调用。 However, Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class. 但是,类的初始化包括执行其静态初始化程序和在该类中声明的static字段(类变量)的初始化程序

That is why, static fields declared in class context always gets instantiated first. 这就是为什么始终在类上下文中声明的静态字段首先被实例化的原因。 For your class which are: int[] arr and int ans . 对于您的班级是: int[] arrint ans static variable ans initialized to the value 0 which is default value of integer. static变量ans初始化为值0 ,它是整数的默认值。 Hence, Instantiating the static array arr has the length 0 and being empty. 因此,实例化static数组arr的长度为0并且为空。 When you are trying to access it in the cubeToss() function using a loop, an AIBE 0 is being thrown as the array has length 0 (or, the array is empty). 当您尝试使用循环在cubeToss()函数中对其进行访问时,由于该数组的长度为0 (或者该数组为空),将引发AIBE 0

So, after reading the ans in the main method in the main method using ans = scan.nextInt(); 所以,读出后ans中的主要方法中的main使用方法ans = scan.nextInt(); , try creating the array in the main method: arr = new int[ans] ,请尝试在main方法中创建数组: arr = new int[ans]

public static int[] arr;

然后仅在从System.in获取ans之后初始化

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

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