-1

I'm in a beginning java course and I have a conditional statement that I'm trying to check without using if/if else statements. I have written it to check for a blank textfield but... it's not working correctly. Here is a copy of the code that I wrote, can anyone please tell me what's wrong?

String nameCheck = (nameField.getText() == "")? "Please enter a name" : "Hello, " + nameField.getText();
jmj
  • 237,923
  • 42
  • 401
  • 438

3 Answers3

1

You'll want to replace

nameField.getText() == ""

with

nameField.getText().equals("");

The double equals operator checks if the two strings are the exact same object, whereas the "equals()" method will check if the strings have the same value.

Feles
  • 155
  • 1
  • 10
  • While I agree that this will work and indeed it does, we(the class) haven't covered this yet, and the teacher frowns a little on using code/statements/syntax that we haven't covered. – user2067237 Feb 13 '13 at 06:10
  • @user2067237 I'm "fairly certain" the teacher covered `equals`. But if not, you should learn about it and use it anyway. `==` is always *incorrect* for equality of non-primitive values. (And it's a darn shame this isn't flagged as a huge warning ..) –  Feb 13 '13 at 06:12
  • LOL, I'm sure she did cover it, it's entirely possible that I zoned a little on that part of the lecture – user2067237 Feb 13 '13 at 06:15
  • If it's necessary, kufudo's solution works just as well (if not better, since it treats an input with all whitespace as blank) but without using `equals`. – Feles Feb 13 '13 at 06:17
  • Just went back through the lecture slides from when we covered the conditional string checking, she did indeed cover .equals, thank you very much for refocusing my attention on the solution – user2067237 Feb 13 '13 at 06:25
1

A better approach may be:

String nameCheck = (nameField.getText().trim().length() == 0)? "Please enter a name" : "Hello, " + nameField.getText();

This checks to see if the string is empty or full of white-spaces.

kufudo
  • 2,803
  • 17
  • 19
0
String nameCheck = (nameField.getText().equals(""))? "Please enter a name" : "Hello, " + nameField.getText();
Bnrdo
  • 5,325
  • 3
  • 35
  • 63