bitmoe
bitmoe

Reputation: 391

Beginners Java Question (string output)

So I'm reading input from a file, which has say these lines:

       NEO
You're the Oracle?
       NEO
Yeah.

So I want to output his actual lines only, not where it says NEO. So I tried this:

if(line.trim()=="NEO")
    output=false;
   if (output)
    TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the line if 'output' is true

But thats not working out. It still prints NEO. How can I do this?

Upvotes: 3

Views: 436

Answers (5)

Déjà vu
Déjà vu

Reputation: 28850

In Java, Strings are objects. And the == operator checks for exact equality.

In other terms

final String ans = line.trim();
final String neo = "NEO";
if (ans == neo)  ... 

implies you want to check that the ans and the neo objects are the same. They are not, since Java allocated (instantiated) two objects.

As other said, you have to test for equality using a method created for the String object, that actually, internally, checks the values are the same.

if (ans.equals(neo)) ...

Upvotes: 2

zigdon
zigdon

Reputation: 15073

Strings are objects in Java. This means you can't just use the == operator to compare them, since the two objects will be different even if they both represent the same string. That's why the String object implements an equal() method, which will compare the contents of the objects, instead of just their memory addresses.

Reference

Upvotes: 4

Sean
Sean

Reputation: 7747

When comparing strings in Java you have to use the equals() method. Here's why.

if ( "NEO".equals(line.trim() )

Upvotes: 7

Ibrahim
Ibrahim

Reputation: 1261

try the following:

if(line.trim().equals("NEO"))

Upvotes: 1

Dave McClelland
Dave McClelland

Reputation: 3413

I think you're looking for line.trim().equals("NEO") instead of line.trim() == "NEO"

That said, you can get rid of the output variable by instead doing

if(!line.trim().equals("NEO"))
{
    TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the if it isn't "NEO"
}

Upvotes: 5

Related Questions