0

I am taking in a String of a movie's release year, and an ArrayList of films (String title, int release year, enum genre etc...). The parameter String year is the users input of search which will be compared to each film to find a film that has the matching release year. The matches will be saved into an ArrayList. By keeping the parameters as (String year, ArrayList films), how can I compare each film's year with the user's input of a year to search for? I have tried casting these but was unsuccessful.

public ArrayList<Film> compareYear(String year, ArrayList<Film> films)                          
{
    ArrayList<Film> yearMatches = new ArrayList<Film>();
    for(Film f : films)                   //search through ArrayList of films
    {
        int years = f.getYear();         //gets the year for each film and compares it to user input search "year"
        if(years == year) {
            yearMatches.add(f);
        }
    }
    return yearMatches;
}
Caiz
  • 49
  • 1
  • 2
  • 7

3 Answers3

3

You can use Integer.parseInt() on the string version, to convert it to an integer before doing your comparison:

if (years == Integer.parseInt(year))

Or you could use String.valueOf on the int version of the year, to convert it to a string:

if (String.valueOf(years).equals(year))
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

you can use Integer.parseInt(String value) to convert a string to an int. i also noticed that your method returns a non existing list of results (releaseYearMatches which has to be yearMatches), so i fixed that for you aswell

public ArrayList<Film> compareYear(String pYear, ArrayList<Film> pFilms)                          
{
    int year = Integer.parseInt(pYear); 
    ArrayList<Film> yearMatches = new ArrayList<Film>();
    for(Film f : pFilms) {
        if(f.getYear() == year)
            yearMatches.add(f);
    }
    return yearMatches;
}
FrankK
  • 482
  • 8
  • 23
0

Convert the string year to an int year before comparing. Replace your code block with below code block, hope it will help

public ArrayList<Film> compareYear(String year, ArrayList<Film> films)                          
{
    int yearInt = Integer.parseInt(year);
    ArrayList<Film> yearMatches = new ArrayList<Film>();
    for(Film f : films)                   //search through ArrayList of films
    {
        int years = f.getYear();         //gets the year for each film and compares it to user input search "year"
        if(years == yearInt) {
            yearMatches.add(f);
        }
    }
    return releaseYearMatches;
}