1

As my title says. I need to search through a file for a string. When its found, I need the next line. It's a file like this:

hello

world

When "hello" is found, "world" needs to be returned.

File file = new File("testfile");
Scanner scanner = null;
try {
  scanner = new Scanner(file);
} catch (FileNotFoundException e) {
  e.printStackTrace();
}

if (scanner != null) {
  String line;
  while (scanner.hasNextLine()) {
    line = scanner.nextLine();
    if (line == "hello") {
      line = scanner.nextLine();
      System.out.println(line);
    }
  }
}

It reads through the file but it doesn't find the word "hello".

Community
  • 1
  • 1
Whhoesj
  • 13
  • 2
  • 4
  • 1
    possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jlordo Feb 23 '13 at 20:17

3 Answers3

5
if (line == "hello") {

should be

if ("hello".equals(line)) {

You have to use equals() method to check if two string objects are equal. == operator in case of String(and all objects) only checks if two reference variables refer to the same object.

PermGenError
  • 45,977
  • 8
  • 87
  • 106
1
if (line == "hello")

should be changed to

if (line.contains("hello"))
Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
Vicky
  • 5,098
  • 2
  • 33
  • 31
0

Instead of using == operator to compare two strings use if(line.compareTo("hello") == 0)