简体   繁体   中英

Java scanner input into array

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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