0

My question relates to how readLine() affects the current position within a file.

Let's say I have a file which has the following in it:

1

if I say

r.readLine()

then it will return "1"

If I do another

r.readLine()

It will return 'null' as there is only one line.

So - if I check the line in an while statement like so:

while (r.readLine!=null){
//Do something here

}

So this should run until it hits a null line then exit.

However, if I want to do something like:

String line;

if ((line = r.readLine()).equals("1"))
//Then do something....
else if ((line = r.readLine()).equals("2"))
//Then do something else

What happens is that obviously,by the time I get to the 2nd check, the read position has moved to the next line.

I tried doing something like this:

String line = r.readLine();
if (line=='1')
//do Something
else if (line=="2")
//do something else.

...However, with this I get some very bizarre results. If can confirm with a System.out.println command that the string 'line' is equal to say, 1 (or whatever value). but when I try to use it in an if statement, the condition never seems to trigger....

Any help here would be appreciated.

Zippy
  • 3,826
  • 5
  • 43
  • 96
  • In first snippet, you are comparing your strings correctly using `equals`, why you changed it to `==` in 2nd snippet? – Rohit Jain Jul 11 '13 at 15:53
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Rohit Jain Jul 11 '13 at 15:55
  • @RohitJain, maybe, but when I asked the question, I didn't know that I wasn't comparing the strings correctly, hence I didn't ask 'how do I compare strings' - if you see what I mean! – Zippy Jul 11 '13 at 16:26

2 Answers2

3
if (line=='1')
//do Something
else if (line=="2")
//do something else.

== is used for comparing references or primitive types, you can test for String equality by using equals():

String x = "hello";
String y = "hello";

Now x == y will be true, becuase they refer to the same object in the string pool

String x = "hello";
String y = new String("hello");

Now x == y will be false, because they are not pointing to the same object anymore, one is in the string pool, while the other is not.

To test properly use equals(String):

String x = "hello";
String y = new String("hello");

x.equals(y);

will evaluate to true

epoch
  • 16,396
  • 4
  • 43
  • 71
1

You're using the wrong type of string comparison. In your second example you should use line.equals(), like you do in the first example, instead of line==. That should fix the problem.

Right now, it's testing if the two strings are the same object, not whether they contain the same values.

resueman
  • 10,572
  • 10
  • 31
  • 45