简体   繁体   中英

Printing out strings in an array while not printing the null, Java

When I run my method to print out the array, it will give me a NullPointerException and I have no idea how to get it to just print what I want. Let's say I want Array[0] to be "Sally" and Array[3] to be "Jeff", I want it to print out 0, Sally 3, Jeff. While leaving all the null slots of the array alone.

Here's my code:

public void printAll()
{       
    for(int i = 0; i <= 10; i++)
    {
        if(seats[i].equals(null))
        {
            System.out.print(i + " , " + seats[i] + "\n");              
        }

    }
}

Any help would be greatly appreciated, if I'm being too vague I can reply with more details.

You need:

if (seats[i] != null)

Using equals will cause a de-reference, which is exactly what you're trying to avoid.

You should not use:

if(seats[i].equals(null))

That condition will itself throw a NPE . You should use:

if(seats[i] != null)

Change if(seats[i].equals(null)) to if(seats[i] != null) or if(seats[i] == null) to avoid NPE.

Because, if seats[i] is null you cannot call methods on null references.

You may want to use the following: (you were checking equality of objects, not whether the array item was null.

public void printAll()
{   
...
    if (seats != null) {
        for (int i=0; i < seats.size(); i++) {
            if (seats[i] != null) {
                System.out.println(i + ", " + seats[i]);  
            }
        }
    }  

}
if(seats[i].equals(null)) {
  System.out.print(i + " , " + seats[i] + "\n");              
}

This is causing your null pointer exception because seats[i] is equal to null. When you have a null object, you can't reference it. At all. This is logical because if you have nothing, then you can't ask what it has.

To fix this, the best way to check if something is equal to null is by going if(Object == null) and if it ISN'T null then, if(Object != null) . These are very common through any code you may have.

Jarod.

public static void printAll(){

  String[] seats={"Jerry","chen","Jack"};
  for(int i = 0; i <seats.length; i++)
  {

if(!seats[i].equals(null))
    {
        System.out.print(i + " , " + seats[i] + "\n");              
    }  

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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