0

I am a novice programmer and have a basic question against if-else loop. I have a program that only gives else output and does not check my if condition. I guess its a syntax error and I am not able to figure it out.

public class adddeed 
{
private User user = new User();
public void showdemo()
{
    Form hi = new Form("Deed", BoxLayout.y());
    TextField first = new TextField("","Enter Description");
    Button b=new Button("Back");
    Button g=new Button("Go");
    String s=first.getText();
    DBHandler db=new DBHandler();
    g.addActionListener(e -> 
    {
        if(s.equals(null))
        {
            Dialog.show(null,"Please Enter a Deed","OK",null);
        }
        else
        {
        Dialog.show(null,"Deed Uploaded Successfully","OK",null);
        }
    });
    b.addActionListener(e -> 
    {
        new Home(user).show();
        //new adddeed().showdemo();
    });
    hi.add(first);
    hi.add(b);
    hi.add(g);
    hi.show();
}
}

Expected result should be when I don't enter anything in textfield, and press GO, it should say "please enter a deed." Actual result is every time I press Go whether the textfield is empty or not empty, it shows "Deed Uploaded Successfully".

  • I'm not a Java programmer but I suspect that you need to change your if conditional check to `if(s.equals(""))`, as `""` and 'null` are not equivalent. `""` is a blank string containing no characters, `null` is an undefined string. – bdx Apr 06 '19 at 04:43

2 Answers2

1

getText() function will not return null, it returns an empty string. So s.equals(null) will be falls always. Try checking if it's empty string or not.

Bharath N
  • 61
  • 7
  • Ive tried the code as you suggested, **if(s.equals(""))** now it runs my if loop but does not give desired output for else. Like, If I dont Enter anything, it says "Please Enter a Deed" and if I dont enter anything then also it says "Please Enter a Deed". It says the same thing. –  Apr 06 '19 at 06:11
  • It's better to use s.isEmpty () function to check if string is empty rather than what you are checking. Try this. – Bharath N Apr 06 '19 at 13:17
0

I was doing it wrong, instead of storing the string in a variable I did it like this

if(first.getText().equals("") )
            {

                Dialog.show(null,"Please Enter a Deed","OK",null);

            }