I often have a problem picking up what movie I should watch. So, I decided to make a simple program to randomize my pick but got stuck on the first step. I want to know how to assign Strings - that are the movie names- to an array. Here is my unfinished code
Scanner input = new Scanner(System.in);
System.out.println("How many movies are you considering?");
int number = input.nextInt();
String[] movies = new String[number];
System.out.println("Enter movie titles...");
for(int i=1; i <= number; i++){
System.out.print(i + "- ");
movies[i] = input.next();
System.out.println();
}
Your code is already doing that. However, you are getting an
ArrayIndexOutOfBoundsException
because your loop is set up to insert values into the array up to an index which does not exist.Array indices are zero-based. This means that, if you have an array of size 5, its indices are numbered 0, 1, 2, 3, and 4. You are currently treating the array as if it was one-based; that is, as if an array of size 5 had indices 1-5 rather than 0-4.
To fix this,
i
should initially be equal to0
, and your loop should terminate wheni < number
instead ofi <= number
.