• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help with an illogical logical statement  RSS feed

 
Greenhorn
Posts: 4
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need some help to understand why a logical statement is not working as I expect it should.
I am very new to Java and am creating a simple program that uses a client and server class. The code below is from the server class.

The client class asks the user to input a student’s name and test scores. The server class validates the user input, amongst other things.

To test the validateData() method, I input an empty string as a student’s name when the client class asked me to. (ie.simply hit the enter key).

However the logical while statement below never evaluates as true and always displays the negative condition action (ie “This is the else statement”). I have also tried using an if-else configuration but the same thing happens.

I tried reversing the problem and using while (name != "") and entering a name eg Bob. In this case the statement will evaluate as true and return the positive condition action and print “The student’s name has not been entered.”

This problem is tying me up in knots and I don’t know how to resolve it. I appreciate your help.


 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dwaine. Welcome to The Ranch!

Your problem is using == to check for String equality. But that checks to see if they're the same object, not if they have the same value. You need to use the equals() method instead:
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or in this case,
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or the method in the String class called isEmpty() or similar. It probably uses a length == 0 test like what Rob posted. Beware, that method is only available in the newer versions of Java™.
 
Dwaine McMaugh
Greenhorn
Posts: 4
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all for your suggestions. I am not tied up in knots anymore.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!