Frage

I am wondering why the 2nd if statement is not being evaluated to true...

 while ((tmp = yearReader.readLine()) != null) {
        if(tmp.length() >= 22){
            System.out.println(tmp.substring(0, 12));
            if(tmp.substring(0, 12) == "<li><a href="){
                System.out.println("This should print...");
            }
        }
    }

Prints this...

 <li><a href=
 <li><a href=
 <li><a href=
War es hilfreich?

Lösung

Because you can't compare String objects with == operator.

In Java, == operator compare instances for objects. In your case, they're obviously not equal. So, change your == for equals() instead:

if("<li><a href=".equals(tmp.substring(0, 12)))

but be aware that equals() can't be invoked on null references, as it will throw a NullPointerException. You must check if instance is not null before invoking it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top