2015-05-27 115 views
0

所以我查找了一些關於這個問題的其他線程,好像我應該能夠使用常規比較運算符來檢查這個問題。檢查字符串數組元素是否爲空

How to check if my string is equal to null?

Java, check whether a string is not null and not empty?

然而,即使我的計劃說,該字符串爲空,後來通過與該字符串不是空的條件執行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

回答

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

額外;導致以下塊總是執行(不管if語句的評估),因爲它結束了if語句。去掉它。

0

問題是';'在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