Home » Java » Code not working. Ask user for 2 characters and search text file for strings that start with those two characters

Code not working. Ask user for 2 characters and search text file for strings that start with those two characters

Posted by: admin August 10, 2018 Leave a comment

Questions:

The goal of this code is to ask the user for 2 characters, and output all the movies starting with those two characters from a text file. Should I make a new method for getTitle()? In MovieUsage it doesn’t work right whether I use contains or equals. Not sure what to do after this. Any help is appreciated.

public class Movie
{
    private String name;

    public Movie (String name)
    {
        this.name = name;
    }

    public static ArrayList<Movie> loadDatabase() throws FileNotFoundException {
        ArrayList<Movie> list = new ArrayList<>();

        File f = new File("db.txt");
        Scanner inputFile = new Scanner(f);

        while (inputFile.hasNext())
        {
            String name = inputFile.nextLine();
            int year = inputFile.nextInt();
            inputFile.nextLine();
            String genre = inputFile.nextLine();

            Movie m = new Movie(name);
            list.add(m);
        }
        return list;
    }
       public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String toSTring()
    {
        return name;
    }
}

public class MovieUsage
{
    public static void printRandomMovie(ArrayList<Movie> database)
    {
        System.out.println("Picking random movie from " + database.size() + " movies");

        Random rng = new Random();
        int subscript = rng.nextInt(database.size());

        System.out.println("Your movie is: " + database.get(subscript));
    }

    public static void printMatchingMovies(ArrayList<Movie> database, String searchString) throws FileNotFoundException {
        int numMatches = 0;

        for (Movie temp : database)
        {
            if (temp.contains(searchString))
            {
                System.out.println(temp);
                numMatches++;
            }
        }
        System.out.println("Number of matches: " + numMatches);
    }

    public static void main(String[] args) throws FileNotFoundException {
        Scanner keyboard = new Scanner(System.in);
        ArrayList<Movie> database = Movie.loadDatabase();

        System.out.println("Movie search by two characters. Enter two characters.");
        String searchString = keyboard.nextLine();

        System.out.println("Movies that start with " + searchString);

        printMatchingMovies(database, searchString);
    }
}

Thank you for the help in advanced.

Answers: