user3286337
user3286337

Reputation: 1

Java: How to compare if statement with object?

Hey Im trying to fill in different slots of this table with the variable f, however I need to do some checks on the row and column it is in before it is put in. I do not know how to change the if statement to make it work, it keeps giving me the null pointer exception. Please help :)

This is the part of the code that needs fixing.

for (int row1 = 0; row1 < data.length; row1++)
        {
            for (int col1 = 0; col1<data[0].length; col1++)
            {
                if(col1%2 != 0)
                {
                    data[row1][col1]= "day" + d;
                    d++;  
                }
                else
                {   
                    Integer f = new Integer(1);
                    int col2 = 0;
                    int row3 = 0;
                    boolean rows;
                    for (int row2 = 0; row2 < data.length; row2++)
                    {
                        if(data[row2][col2].equals(f))//this one
                        {
                            rows = false;
                        }
                        else
                        {
                            rows = true;
                        }
                        col2++;
                        if(col2 >= col)
                        {
                            col2 = 0;
                        }

                        for (int col3 = 0; col3<data[0].length; col3++)
                        {
                            if(f > a)
                            {
                                f = 1;
                            }
                            else if(rows == true && data[row3][col3].equals(f))//this one

                         {
                                data[row3][col3]= f;
                            }
                            f++;
                            row3++;
                            if(row3 >= row)
                            {
                                row3 = 0;
                            }
                        }
                    }
                }
            }
        }

Upvotes: 0

Views: 90

Answers (1)

spiderman
spiderman

Reputation: 11112

As @mikemil and @Miguel suggested, provide more code and refactor your code.

If this is the line that is throwing Null Pointer Exception,

if(data[row2][col2].equals(f))

that means data[row2][col2] is null.

Check for null first and then perform equals()

or try like this

if(f.equals(data[row2][col2]))

Upvotes: 2

Related Questions