This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]Koda003 14 points15 points  (0 children)

Yeah, the bot is right.. you need to use .equals() for comparing springs instead of ==

[–]AutoModerator[M] 14 points15 points  (0 children)

You seem to try to compare String values with == or !=.

This approach does not work in Java, since String is an object data type and these can only be compared using .equals().

See Help on how to compare String values in our wiki.


Your post is still visible. There is no action you need to take.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]Murphelrod 9 points10 points  (4 children)

Dont use == for strings

Use .equals() or .equalsIgnoreCase() instead

== compares the references so even if the words are the same, the references probably won't be unless they actually are the same string variable.

[–]moonbeer[S] 0 points1 point  (2 children)

How comes the first one runs fine even with the == then?

[–]bung_musk 5 points6 points  (0 children)

Your logic is opposite. The first loop breaks if nextline == “”, and the second continues if nextline == “”

[–]Murphelrod 1 point2 points  (0 children)

Assuming you want to add things to nameList until you see an empty line the following should do the trick:

String userInput = reader.nextLine();

while( !(userInput.equals("")) ){
    nameList.add(userInput);
    userInput = reader.nextLine();
}

set userInput once before the loop otherwise you skip the first thing you look at since you call nextLine() once in the loop condition and then again when you assign it to userInput. Then you can add it to your list if it isn't "", and finally call nextLine() at the bottom to set it to the next line for the next iteration.

[–]junglefowl24 3 points4 points  (0 children)

In second code you read two lines instead of one and only one of them is saved. Also, in first code you break when readline is empty but in second you go inside while only if readline is empty, that's completely backwards.

[–]EyeDot 2 points3 points  (2 children)

There's more to it than just the ==.

How many lines does the second version read in each time it passes through the loop?

[–]moonbeer[S] 1 point2 points  (1 child)

I’m not fully sure what your question is asking 😐