简体   繁体   English

我不明白为什么这个简单的声明不起作用

[英]I don't understand why this simple statement isn't working

So I'm basically finished with a program, and at the end of it I'm printing Strings from an array to a file. 因此,我基本上完成了一个程序,最后,我将字符串从数组打印到文件中。 The array may contain null values, so I'm checking for null before I print, but I keep ending up with 1 null at the very end of the file... 该数组可能包含空值,因此我在打印前检查是否为空,但在文件的最后我一直以1空结尾。

Here's the code I'm using to check for null 这是我用来检查null的代码

for(int i=0;i<array2.length;i++)
{
    if(array2[i] != null)
        out.println(array2[i]);
}

I know that the array contains multiple instances of null, but only 1 is being printed. 我知道该数组包含null的多个实例,但是仅输出1个。 I tried using the debugger and when array2[i] == null, it still entered the conditional statement... 我尝试使用调试器,当array2 [i] == null时,它仍然输入条件语句...

So I added a println statement to help me see what's going on. 因此,我添加了一个println语句来帮助我了解发生了什么。 It now looks like this: 现在看起来像这样:

for(int i=0;i<array2.length;i++)
        {
            if(array2[i] != null)
            {
                System.out.println("Adding " + array2[i]);
                out.println(array2[i]);
            }

Just after printing all the String values to the console, it prints "Adding null" so I know it's happening here in this if statement. 在将所有String值打印到控制台之后,它将打印“ Adding null”,因此我知道它在if语句中发生。 Why is this happening??? 为什么会这样呢???

The debugger is not always clear as to whether it has entered an if condition or not. 调试器对于是否已进入if条件并不总是很清楚。 I don't believe this code is entering the if condition which it might appear it is and your null is probably coming from another line of code. 我不认为此代码正在输入可能出现的if条件,而您的null可能来自另一行代码。

You could write the code as 您可以将代码编写为

for(ElementType e: array2.length)
    if(e != null)
        out.println("[" + e+ ']'); // extra text for debugging.
// I suspect your `null` will still be on a line of its own

Arent you also missing a set of brakets for the if statement?? 阿伦特(Arent),您还为if语句缺少了一些障碍?

for(int i=0;i<array2.length;i++) 
{ 
  if(array2[i] != null) 
  {
    out.println(array2[i]); 
  }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM