-1

I created this code to check whether the text field of calculator has any content. If content is present in the text field, then it should display ".". Otherwise, it should display "0." in the text field. The problem is that the if condition always evaluates to false.

private void dotActionPerformed(ActionEvent evt){
    String dott=display.getText();
    if(dott==null)
    {
        display.setText(display.getText()+"0.");
    }
    else
    {
        display.setText(display.getText()+dot.getText());   
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Vishnu A
  • 1
  • 1

7 Answers7

2

The string will be "", not null. Use dott.isEmpty() to see if dott has no contents. Here is another post with more details on the difference between .compareTo("") and .isEmpty().

Community
  • 1
  • 1
xandermonkey
  • 4,054
  • 2
  • 31
  • 53
1

I think you can do :

if(dott.equals(""))
Florent.M
  • 74
  • 8
0

try this String method:

if(dott.isEmpty())
    //your code

or you can also use:

if(dott.compareTo("")==0)
    // your code
Kaushal28
  • 5,377
  • 5
  • 41
  • 72
0

Try something like:

 String dott = ...;
 dott.isEmpty();

or

 dott.equals("");
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0
String dott=display.getText();
if(dott==null) // original code; should use isEmpty()
{
    display.setText(display.getText()+"0.");
}

But you already know that display.getText() is empty, so why execute it again? Same for the "else" clause - you already know the value. So you should just write:

String dott=display.getText();
if(dott.isEmpty()) {
    display.setText("0.");
} else {
    display.setText(dott+dot.getText());   
}

Or more concise:

   String dott=display.getText();
   String text = dott.isEmpty() ? "0." : dot.getText();
   display.setText(text);

or even:

   String dott=display.getText();
   display.setText( dott.isEmpty() ? "0." : dot.getText() );
FredK
  • 4,094
  • 1
  • 9
  • 11
0

Replace if(dott==null) by

if(dott.equals(""))

Shiv Buyya
  • 3,770
  • 2
  • 30
  • 25
0

You can use StringUtils of apache if you want. Link : https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

  private void dotActionPerformed(ActionEvent evt){
        String dott=display.getText();
        if( StringUtils.isEmpty(dott))
        {
            display.setText(display.getText()+"0.");
        }
        else
        {
            display.setText(display.getText()+dot.getText());   
        }
    }
sauumum
  • 1,638
  • 1
  • 19
  • 36