TheRealET
TheRealET

Reputation: 11

getting ArrayIndexOutOfBoundsException java

my program calculates some stuff using multi-threading. I've tested it while giving the array a hardcoded length like 10, and my program works fine. However the way i'm doing it now using 'length', I am getting an "array out of bounds exception" on this line: array[i] = Integer.parseInt(splited[i]); before i get any output and can't figure out why. can anyone help? thank you.

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
    } 
}

Upvotes: 0

Views: 48

Answers (1)

Peter Tillemans
Peter Tillemans

Reputation: 35331

you initialise the array statically with

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

at the time of initialization length is 0, so you get a 0-sized array --> out of bound the first time you try. When changing length afterwards, this will not dynamically reallocate a new array.

You should allocate the array when you know the length:

    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]);
    }

Now a new array will be made just right for the line. Do not worry about the old one, it will be garbage collected.

Upvotes: 2

Related Questions