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?