簡體   English   中英

檢查String數組元素是否為null

[英]Check if String array element is null

因此,我研究了有關此問題的其他線程,似乎我是否應該可以使用常規比較運算符進行檢查。

如何檢查我的字符串是否等於null?

Java,檢查字符串是否不為null且不為空?

但是,即使我的程序說字符串為空,它以后也會通過執行if語句(字符串不為空)與之矛盾。 更清楚地說,這是我的完整程序:

package bank;

public class HowCheckForNull {

    static void showDates(String[] dates){
        for(int i = 0; i < dates.length; i++){
            System.out.println(dates[i]);
            System.out.println(dates[i] == null);
            System.out.println(dates[i] == (String) null);
            System.out.println(dates[i] != null);
            if(dates[i] != null);{ //This should not execute!?
                System.out.print("A transaction of X$ was made on the " + dates[i] + "\n");
            }
        }
        System.out.println("");
    }

    public static void main(String args[]){
        String[] dates = new String[3];
        showDates(dates);
    }
    }

輸出:

null
true
true
false
A transaction of X$ was made on the null
null
true
true
false
A transaction of X$ was made on the null
null
true
true
false
A transaction of X$ was made on the null

有兩件事讓我感到困惑,即使日志記錄表明相反,為什么執行if語句,以及dates[i]是否等於null(String) null怎么可能?

if(dates[i] != null);
                    ^

額外的; 導致下面的塊始終執行(無論是否對if語句進行評估),因為它結束了if語句。 去掉它。

問題是 ';' if(condition); 結束該語句並以正常方式處理其余代碼,而不管任何條件如何。

    package bank;

    public class HowCheckForNull {

        static void showDates(String[] dates){
            for(int i = 0; i < dates.length; i++){
                System.out.println(dates[i]);
                System.out.println(dates[i] == null);
                System.out.println(dates[i] == (String) null);
                System.out.println(dates[i] != null);
                if(dates[i] != null){ //Now it will not execute.
                    System.out.print("A transaction of X$ was made on the " + dates[i] + "\n");
                }
            }
            System.out.println("");
        }

        public static void main(String args[]){
            String[] dates = new String[3];
            showDates(dates);
        }
    }

輸出量

null
true
true
false
null
true
true
false
null
true
true
false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM