0

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
    } 
}
1
  • 1
    Think about what the value of length is when you initialize array. Commented May 19, 2015 at 22:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.