0

I'm currently doing coding online to learn coding and am doing the Battleship problem. In this problem you're given methods and the parameters they accept in code.

I am stuck on a problem where the user inputs a row and column and the code verifies whether a row and column were inputted.

// Has the location been initialized
public boolean isLocationSet()
{
    if(row == null  && col == null)
    {
        return false;
    }

    return true;
}

The error I get says: Incomparable types int and (it cuts off but I'm assuming it means null or boolean)

How would I be able to say, if the expected ints row and column are empty then return false, otherwise return true?

Steve Smith
  • 2,244
  • 2
  • 18
  • 22
  • What are `row` and `col`? The error implies that they are `int` values, which can *never* be `null`. So the comparison is invalid and can never be `true`. – David Feb 14 '17 at 13:55
  • It's not clear what you are asking. One approach would be to use an Integer object initialized to null instead of an int which cannot be null. – Patrick Parker Feb 14 '17 at 14:09

2 Answers2

0

The conflict is due to the difference between primitive types and reference types in Java. Java has some built-in types (int, boolean, float, char, etc) that can never be null and can never be inherited from. It looks like you are trying to compare an int (row) with null. This is an error because an int can never be null.

You may want to use Integer instead, which is a reference type than can be automatically converted to int.

Community
  • 1
  • 1
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
0

int cannot be null. Nor can a lot of other primitive types. Adjust your conditional accordingly:

private int row = 0;
private int col = 0;

// Has the location been initialized
public boolean isLocationSet()
{
    if(row <= 0 || col <= 0)
    {
        return false;
    }

    return true;
}

I would also use an OR operator instead of an AND. Presumably your row and col variables are initialized as 0. So, for instance, if row=1 but col=0 then this isLocationSet() method will return false, which would be expected since one of the location variables, row and col, has not been set yet.

You can use Integer instead if you want to check for null:

private Integer row = null;
private Integer col = null;

// Has the location been initialized
public boolean isLocationSet()
{
    if(row == null || col == null)
    {
        return false;
    }

    return true;
}
jseashell
  • 745
  • 9
  • 19