获取 ArrayIndexOutOfBoundsException java

getting ArrayIndexOutOfBoundsException java

我的程序使用多线程计算一些东西。我已经测试了它,同时给数组一个硬编码的长度,比如 10,我的程序运行良好。然而,我现在使用 'length' 的方式在这一行上得到一个 "array out of bounds exception":array[i] = Integer.parseInt(splited[i]); 在我得到任何输出并且无法弄清楚原因之前。谁能帮忙?谢谢你。

import java.util.*;

public class Stats {

    static int length;
    static int[] array = new int[length];


    private static class WorkerThread extends Thread 
    {  

       //...some stuff with threads 
    } 


    public static void main(String[] args) { 


        Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter the integers: ");
        String line = keyboard.nextLine();
        //split line by space and store each number as a sting 
        //in a string array
        String[] splited = line.split("\s+");
        //get length of string array of numbers
        length = splited.length;

        //convert string to int and store in int array
        for(int i=0; i<length; i++)
        {
            array[i] = Integer.parseInt(splited[i]);
        }

        //...some stuff with threads
    } 
}

你用

静态初始化数组
static int length;
static int[] array = new int[length];

在初始化时长度为 0,因此您得到一个大小为 0 的数组 --> 第一次尝试时超出范围。之后更改长度时,这不会动态重新分配新数组。

知道长度就应该分配数组:

    length = splited.length;
    array = new int[length];

    //convert string to int and store in int array
    for(int i=0; i<length; i++)
    {
        array[i] = Integer.parseInt(splited[i]);
    }

现在将制作一个新数组,正好适合该行。不用担心旧的,它会被垃圾收集。