Check a Scanner.nextLine() with the if statement. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Check a Scanner.nextLine() with the if statement.

Well, I have a little question that the title already says, how to check a String that receives the Scanner.nextLine() with the if statement. For example, "msg" is the var that receives the input, I've typed "if (msg === "Hi")" it should print "Hello", but when I put "Hi" in the input box it doesn't prints nothing. I've tried print the msg and it prints "Hi" as I typed. Is there a way to do that? Below is the code. https://code.sololearn.com/cJ5GC8fne9SV/?ref=app.

25th Mar 2019, 12:56 AM
João Pedro
João Pedro - avatar
5 Answers
+ 16
In Java, you should use .equals() for string comparisons instead of ==. This is because == checks if both strings refer to the same object, while the .equals() method checks for equality in terms of the string contents. if (msg.equals("Hi"))
25th Mar 2019, 1:03 AM
Hatsy Rei
Hatsy Rei - avatar
+ 12
<, >, <= and >= can only be used with numbers and characters. They cannot be used with Strings, booleans, arrays or other compound types since there's no well-defined notion of order for these objects. Here is an example of testing objects for equality with equals() https://code.sololearn.com/clfOay4iwY7p/?ref=app
25th Mar 2019, 11:49 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 2
With string you must use equals()
25th Mar 2019, 2:51 PM
Ha Nguyen
Ha Nguyen - avatar
12th Apr 2019, 8:46 AM
Muneer
Muneer - avatar
- 1
thx everybody.i had this probleme me too but now it solved
31st Mar 2019, 5:41 PM
caida dodosy
caida dodosy - avatar