简体   繁体   English

如果条件正常,为什么这不起作用?

[英]Why doesn't this if condition work?

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." 否则,它应显示为"0." in the text field. 在文本字段中。 The problem is that the if condition always evaluates to false. 问题在于if条件始终评估为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());   
    }
}

The string will be "" , not null. 字符串将为"" ,不为null。 Use dott.isEmpty() to see if dott has no contents. 使用dott.isEmpty()查看dott是否没有内容。 Here is another post with more details on the difference between .compareTo("") and .isEmpty(). 是另一篇有关.compareTo("").isEmpty().之间的区别的详细信息.isEmpty().

我认为您可以:

if(dott.equals(""))

try this String method: 试试这个String方法:

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

or you can also use: 或者您也可以使用:

if(dott.compareTo("")==0)
    // your code

Try something like: 尝试类似:

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

or 要么

 dott.equals("");
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? 但是您已经知道display.getText()为空,那么为什么要再次执行它呢? Same for the "else" clause - you already know the value. 与“ else”子句相同-您已经知道该值。 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() );

Replace if(dott==null) by 将if(dott == null)替换为

if(dott.equals("")) if(dott.equals(“”))

You can use StringUtils of apache if you want. 您可以根据需要使用apache的StringUtils Link : https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html 链接: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html : 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());   
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM