How to manually plug in values in an array of strings?

177 views Asked by At

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();
  }
1

There are 1 answers

8
Bethany Louise On

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 to 0, and your loop should terminate when i < number instead of i <= number.