2015-05-27 81 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