0

I am trying write code which will read input from a txt file and stop after reaching a certain line.

This is my current code:

File data = new File("text.txt");
try {

    Scanner load = new Scanner(data);

    while (load.hasNextLine()) {
        String line = load.nextLine();
        if (line == "end") break;
        System.out.println(line);
    }

    load.close();

} catch (FileNotFoundException e) {
    System.out.println("File not found");
}

This is the text contained in text.txt:

line1
line2
line3
end
line5
line6

I expected it to only output the lines before the line end, but instead, every line was printed. How can I fix this issue?

BenMan95
  • 175
  • 1
  • 6

1 Answers1

0

for comparing two strings you should use equals instead of == operator. like line.equals("end")

The below code works fine:

File data = new File("text.txt");
try {

    Scanner load = new Scanner(data);

    while (load.hasNextLine()) {
        String line = load.nextLine();
        if (line.equals("end")) break;
        System.out.println(line);
    }

    load.close();

} catch (FileNotFoundException e) {
    System.out.println("File not found");
}
SMortezaSA
  • 589
  • 2
  • 15