Beginner Java question (line output)

So, I am reading the input from a file that says these lines:

       NEO
You're the Oracle?
       NEO
Yeah.

So, I want to output only its actual lines, and 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 that does not work. He still prints NEO. How can i do this?

+3
source share
5 answers

I think what you are looking for line.trim().equals("NEO")insteadline.trim() == "NEO"

However, you can get rid of the variable by outputdoing this instead

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

When comparing strings in Java, you should use a method equals(). Here is why .

if ( "NEO".equals(line.trim() )
+7
source

- Java. , == , , . String equal(), , .

+4

Java . == .

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

, , ans neo . , Java ( ) .

Like all of the above, you need to verify equality using the method created for the object String, which actually internally checks the values ​​to be the same.

if (ans.equals(neo)) ...
+2
source

try the following:

if (line.trim (). equals ("NEO"))
+1
source

Source: https://habr.com/ru/post/1764809/


All Articles