0

I have a homework assignment where you are supposed to be able to search a text document (your moviedatabase) for example "sta" and then print all the movies that have the substring "sta" in them. Although it works just fine until I have more than 6 movies in the database then it doesn't show any results at all.

Java file 1 with another class

public void sökTitel() {
    System.out.print("Ange sökord: ");
    String titel = scanner.nextLine().toUpperCase().trim();
            Lästitelfrånfil.läsTitel(titel);    
}

java file 2

enter code here

package labb5;
import java.io.*;
import java.util.*;
public class Lästitelfrånfil {
    public static void läsTitel (String titel) {
        File fil =new File("filmdatabas.txt");
        Scanner in;
        try {
            in = new Scanner(fil);
            while(in.hasNext()) {
                String line = in.nextLine();
                if(line.contains (titel))
                    System.out.println("Titel: " + (line.substring(0, line.length()-1)) + 
                        " Betyg: " + line.substring(line.length()-1, line.length()) + "/5");
            }
            in.close();
        } 
        catch (FileNotFoundException e) {  
        } 
    }
}

Textfile

STAR WARS 1 4
STAR WARS 2 2
STAR WARS 3 4
STAR WARS 4 3
BATMAN THE DARK KNIGHT 5

If I search for "sta" with only 5 movies in textfile the result is:

Ange sökord: sta
Titel: STAR WARS 1  Betyg: 4/5
Titel: STAR WARS 2  Betyg: 2/5
Titel: STAR WARS 3  Betyg: 4/5
Titel: STAR WARS 4  Betyg: 3/5

If I add more than 7 movies the result is:

nothing
Kebabkalle
  • 13
  • 3

1 Answers1

0

Instead of

File fil = new File("filmdatabas.txt");

try using a FileReader (from java.io package)

FileReader fil = new FileReader("filmdatabas.txt");

(additionally, you could use a BufferedReader and its readLine() method - but this is just additional optimization)

Coronero
  • 160
  • 1
  • 9
  • What is the difference between FileReader and BufferedReader? – Kebabkalle Jan 07 '19 at 12:48
  • I would use the BufferedReader instead of the Scanner. You may want to have a look at this [post](https://stackoverflow.com/questions/2231369/scanner-vs-bufferedreader) Edit: But for your application, Scanner is sufficient – Coronero Jan 07 '19 at 12:53