0

I have a text file which has the string, - "!- =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========" in it as you can see in the code below. IF the text file contains this string I need to read it from the text file and then print it out again. The problem is I cant work out why my code is not printing it.

Any help would be appreciated thanks!

public class Main {

    public static void main(String[] args) throws FileNotFoundException {

        File file = new File("C:/Users/Anton/Pictures/1 x geotransform0.5m shading.txt");

        Scanner scan = new Scanner(file);

            while(scan.hasNext()){
                String str = scan.next();

                if(str == "!-   ===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="){
                    System.out.print(str);
                }
            }
            scan.close();
        }   
}
topher
  • 14,790
  • 7
  • 54
  • 70
Anton James
  • 385
  • 3
  • 6
  • 18
  • When using a debugger, what is `str` when you get to the `if` statement? – Mike Koch Apr 22 '14 at 12:55
  • 5
    Use equals() method of String object instead ==. – DmitryKanunnikoff Apr 22 '14 at 12:55
  • This looks bad `str == `. Take a look at [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). Also `next()` will return only one word. You probably need to use `nextLine()`. – Pshemo Apr 22 '14 at 12:55

2 Answers2

1

use below code, scanner next gives just a word use nextLine instead to read whole line..

Scanner scan = new Scanner(file);
            String str1 = scan.nextLine();

                if(str1.equals("!-   ===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="))
                    System.out.println(str1);
                scan.close();
Karibasappa G C
  • 2,686
  • 1
  • 18
  • 27
0

use this

if(str.equals("!-   ===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========")){
            System.out.print(str);
        }

instead of

if(str == "!-   ===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="){
            System.out.print(str);
        }
Rishi Dwivedi
  • 908
  • 5
  • 19