I have a program in which I need to print out several Movie
objects (represented just by a single String) in an array. I start with a text file that already has five movies inside of it, but in the console, I am to allow the user to expand the array if he/she wants. (I cannot use an arraylist in this problem). I've attempted to design a program that does this, but I get an out of bounds exception each time I try to add a new movie. I also need to check the array to see if there is a duplicate movie object inside it? How can I do that?
Question: How can I allow the user to expand the array and add more movies to the list? How can I check the array to see if there is already a certain movie title inside of it?
public class MovieDriver {
//variable declaration
static Movie[] movies = new Movie[5];
static Scanner scan = new Scanner(System.in);
static int input = 0;
static String title = "";
public static void main(String[] args) throws FileNotFoundException {
//retrieves movie data
getData();
System.out.println("Welcome to the favorite movie program.");
do{
System.out.println("Press 1 to print the list, 2 to add another movie, 3 to end the program.");
input = scan.nextInt();
switch(input) {
case 1:
for(int i = 0; i < movies.length; i++)
{
System.out.println(movies[i].toString());
}
break;
case 2:
System.out.println("Please enter the movie you would like to add to the list:");
title = scan.nextLine();
movies = Arrays.copyOf(movies, movies.length+1);
movies[movies.length] = new Movie(title);
break;
case 3:
System.out.println("Program terminated.");
break;
}
} while (input != 3);
}
// method to retrieve data
public static void getData() throws FileNotFoundException {
// reads in movie data
File MovieData = new File("./src/Movies.txt");
Scanner fileScanner = new Scanner(MovieData);
int i = 0;
// while there is a new line in the data, goes to the next one
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String title = lineScanner.nextLine();
// creates a movie
movies[i] = new Movie(title);
i++;
}
}
}