Reputation: 3293
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?
Upvotes: 1
Views: 8685
Reputation: 200140
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);
Upvotes: 1
Reputation: 116286
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.
Upvotes: 3
Reputation: 421090
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.
Upvotes: 0
Reputation: 61536
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)
Upvotes: 0