Reputation: 2895
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
Upvotes: 0
Views: 190
Reputation: 12880
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!
Upvotes: 3
Reputation: 32468
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
Upvotes: 2