startrak209
startrak209

Reputation: 7

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.

Upvotes: 0

Views: 72

Answers (6)

pretty_monk
pretty_monk

Reputation: 21

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");              
    }  

}

Upvotes: 0

TheBrenny
TheBrenny

Reputation: 527

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.

Upvotes: 0

ErstwhileIII
ErstwhileIII

Reputation: 4843

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]);  
            }
        }
    }  

}

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213261

You should not use:

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

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

if(seats[i] != null)

Upvotes: 1

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

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.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881563

You need:

if (seats[i] != null)

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

Upvotes: 1

Related Questions