我在处理应用程序时犯了编码错误,这是对null引用的测试.我花了几个小时来发现问题是什么,但我不明白的是为什么代码表现如此.
String name = null;
String value = null;
if(name != null && value != null);
{
System.out.println("Values not null");
}
Run Code Online (Sandbox Code Playgroud)
if语句结束了;,这是我的错误,Values not null即使很明显两个值都为空,也会打印出来.谁能解释为什么?
Tom*_*icz 14
这个分号结束一个语句(一个空的),所以你的代码由编译器翻译成这样的:
if(name != null && value != null)
{
//nothing here
}
{
System.out.println("Values not null");
}
Run Code Online (Sandbox Code Playgroud)
换句话说,如果if表达式是true,则它执行空代码块.然后,无论是否if为真,运行时都会继续并运行包含的块System.out.Empty语句仍然是一个语句,因此编译器接受您的代码.
另一个可能发生这种错误的地方:
for(int i = 0; i < 10; ++i);
{
System.out.println("Y U always run once?");
}
Run Code Online (Sandbox Code Playgroud)
甚至更糟(无限循环):
boolean stop = false;
while(!stop);
{
//...
stop = true;
}
Run Code Online (Sandbox Code Playgroud)
我花了几个小时才发现问题所在
好的IDE应该立即警告你这样的声明,因为它可能永远不会正确(就像if(x = 7)在某些语言中).
; 终止声明.
if(name != null && value != null);
Run Code Online (Sandbox Code Playgroud)
相当于:
if(name != null && value != null)
{
}
Run Code Online (Sandbox Code Playgroud)
以下代码只是一段代码.
| 归档时间: |
|
| 查看次数: |
3223 次 |
| 最近记录: |