0

I'm wanting to put the input of a scanner into my array but I am getting the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

my code:

    public static void main(String[] args)
    {
        Scanner scanInput   =   new Scanner(System.in);
        Random randomGen    =   new Random();

        String captureString[]  = new String[] {};

        System.out.println("Please enter some words..");
        captureString[0]  =   scanInput.next();
        captureString[1]  =   scanInput.next();
        captureString[2]  =   scanInput.next();


        System.out.println("You entered: " + captureString[0] + " " + captureString[1] + " " + captureString[2]);

    }

}

I cannot use loops or conditionals (task) so is an array viable for this? or should I just use variables, only reason I want to use an array is because I want to do some string manipulation afterwards which can be a little awkward with variables

1
  • As I write this, you have three good explanations of why this happens. May I suggest you use an ArrayList<String> instead, as this will grow on demand. Commented Mar 15, 2014 at 4:22

2 Answers 2

3

Since you are getting three inputs, i'd suggest. Change it to String captureString[] = new String[3];. This is because, Arrays need to be initialized before they are used. Since you have initialiazed with no values. There will not be any index in it. So, when you access the index 0, you are getting ArrayIndexOutOfBoundsException. Hope it clarifies!

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

Comments

2

Your array captureString has zero capacity. You can't add elements there. Java arrays can't grow, Use ArrayList, if the content intend to be grow

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.