java - Simple if statement problem -
i trying return tostring if true.
i have code:
public void printoutsailings() { (sailing s:sailings) { string hamburg = ("hamburg"); if ((s.getdepartureport()) == hamburg) { system.out.println(s.tostringadjusted()); } } }
however nothing when run method (when should getting something). assume have somehow messed logic or not understood =,== , eq properly, i'm not sure.
there nothing wrong tostring or loop, , i'm not getting compiler or run time errors. it's logic wrong.
if put me right that'd appreciated. thanks.
you should using .equals()
instead of ==
check string
equality. try following:
if ((s.getdepartureport()).equals(hamburg)) { system.out.println(s.tostringadjusted()); }
in short, ==
checks see if 2 strings exact same reference, , .equals()
checks see if 2 strings same.
it should said need use .equals()
checking equality of object
type, not strings. primitive types (int
, double
, char
) should use ==
equality.
to compensate fact departure might null, switch condition around. read - hamburg.equals(s.getdepartureport())
Comments
Post a Comment