Question

I have an ArrayList containing Movies.

ArrayList<Movie>movies = new ArrayList<Movie>();

Movie has a property int movienumber.

The user can select a movie according to the movienumber, by entering the desired number into the console. I store the users choice inside a field moviechoice.

How can I store the user-selected movie in the field Movie moviechosen, according to the users input? Meaning, how can I check if the users input matches the number property of a certain Movie, and then store this Movie-object in the moviechoice field?

Was it helpful?

Solution

To me this sounds like you actually need a Map<Integer, Movie> instead of a List.

Map<Integer, Movie> movies = new HashMap<Integer, Movie>();

// for each movie
movies.put(movie.getNumber(), movie);

...
// retrieving the selected movie
Movie selectedMovie = movies.get(movieNumber);

if (selectedMovie == null)
  System.out.println("Invalid movie number!");

(I assume that movie numbers are unique - I believe this is not a strong assumption, since without this, your list lookup would also be ambiguous.)

Apart from using a Map being more intuitive and clearer, requiring less code, it also offers practically constant time lookup, while List has O(n). If you have a significant number of movies, this is going to make a difference.

OTHER TIPS

You have no choice, in this case, but looping through the ArrayList and compare the value:

for(Movie m : movies){
    if(  m.getTheNumberYouAreTalkingAbout() == numberSelected  ){
        moviechoice = m;
        break;
    }
}

If the number is unique, you may want to previously save all the movies in a HashMap:

Map<Integer, Movie>movies = new HashMap<Integer, Movie>();

And use the key of the Hashmap to save the movienumber. That way you just have to do this:

moviechoice = movies.get(numberSelected);

something like:

for(Movie movie : movies)
{
    if(movie.getMoveiNumber() == moviechoice)
    {
        moviechosen = movie;
    }
}

movieChoice and movieChosen would be better Java names (they follow the standard naming conventions)

How can I store the user-selected movie in the field Movie moviechosen, according to the users input? Meaning, how can I check if the users input matches the number property of a certain Movie, and then store this Movie-object in the moviechoice field?

Something like this should do.

Movie moviechosen = null;

for (Movie m : movies)
    if (m.movienumber == moviechoice)
        moviechosen = m;

if (moviechosen == null)
    System.out.println("Invalid choice!");

You may also want to consider storing the movies in a Map<Integer, Movie>. In that case, you could simply do

Movie moviechoen = movies.get(moviechoice);

However, note that you could only have a single movie object per movienumber.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top