gpt4 book ai didi

java - 检查 String 数组元素是否为 null

转载 作者:行者123 更新时间:2023-12-01 06:43:10 24 4
gpt4 key购买 nike

因此,我查看了有关此问题的其他一些线程,似乎我是否应该能够使用常规比较运算符来检查这一点。

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

最佳答案

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

额外的;导致后面的 block 始终执行(无论 if 语句的评估如何),因为它结束了 if 语句。删除它。

关于java - 检查 String 数组元素是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30477510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com