My java code keeps giving me back StringIndexOutOfBounds for the following code. Need help dealing with this
My java code keeps giving me back StringIndexOutOfBounds for the following code. Need help dealing with this
Movie.java:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Movie
{
public String name;
public int year;
public String genre;
public static ArrayList<Movie> loadDatabase() throws FileNotFoundException {
ArrayList<Movie> result=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, year, genre);
//System.out.println(m);
result.add(m);
}
return result;
}
public Movie(String name, int year, String genre)
{
this.name=name;
this.year=year;
this.genre=genre;
}
public boolean equals(int year, String genre)
{
return this.year==year&&this.genre.equals(genre);
}
public String toString()
{
return name+" ("+genre+") "+year;
}
}
MovieDemo.java:
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class MovieDemo
{
public static void printMatchingMovie(ArrayList<Movie>
int numMatches=0;
for (Movie temp : database) {
if (temp.equals(year, genre)) {
System.out.println(temp);
numMatches++;
}
}
System.out.println("Number of matches: "+numMatches);
}
public static void printMatchingMovies(ArrayList<Movie>database, String inputName)
{
int numMatch=0;
for(Movie temp: database){
if(inputName.substring(0,2).equals(temp.name.substring(0,2))){
System.out.println(temp);
numMatch++;
System.out.println("Number of matches: "+numMatch);
}
else {
System.out.println("No matching movies found!");
}
}
}
public static void main(String[] args) throws FileNotFoundException
{
ArrayList<Movie> database=Movie.loadDatabase();
//printMatchingMovie(database, 2004, "Family");
Scanner keyboard=new Scanner(System.in);
System.out.println("Movie search by characters. Enter two characters.");
String inputName= keyboard.nextLine();
System.out.println("Movies that start with "+inputName);
printMatchingMovies(database, inputName);
}
}
te file db.txt is about 4500 lines of code, but i took a few pics for at least an exapmle of what it is.
some examples:
Movie search by characters. Enter two characters.\n
TmENTER
Movies that start with Tm\n
Tmima ithon\n
Tmima ithon\n
Tmima ithon\n
Tmunot Yafo'iyot\n
Tmunot Yafo'iyot\n
Number of matches: 5\n
Test Case 2
MtENTER
Movies that start with Mt\n
Mtv Base: Touching Base\n
Mtvris gemo\n
Number of matches: 2\n
Step by step
Solved in 3 steps with 1 images