【问题标题】:CodeHS Battleship JavaCodeHS 战舰 Java
【发布时间】:2017-02-14 13:53:13
【问题描述】:

我目前正在在线进行编码以学习编码,并且正在解决战舰问题。在这个问题中,您将获得方法和它们在代码中接受的参数。

我遇到一个问题,用户输入行和列,代码验证是否输入了行和列。

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

    return true;
}

我得到的错误是:Incomparable types int and(它会被切断,但我假设它意味着 null 或 boolean)

如果预期的整数 rowcolumn 为空然后返回 false,我怎么能说,否则返回 true?

【问题讨论】:

  • rowcol 是什么?该错误暗示它们是int 值,它永远不会null。所以比较无效,永远不能是true
  • 不清楚你在问什么。一种方法是使用初始化为 null 的 Integer 对象,而不是不能为 null 的 int。

标签: java


【解决方案1】:

int 不能是 null。许多其他原始类型也不能。相应地调整你的条件:

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

我也会使用 OR 运算符而不是 AND。大概你的rowcol 变量被初始化为0。因此,例如,如果 row=1col=0 则此 isLocationSet() 方法将返回 false,这是可以预期的,因为尚未设置位置变量之一 rowcol

如果你想检查 null,你可以使用 Integer 代替:

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

【讨论】:

    【解决方案2】:

    冲突是由 Java 中的 the difference between primitive types and reference types 引起的。 Java 有一些内置类型(intbooleanfloatchar 等)永远不能是null,也永远不能被继承。您似乎正在尝试将 int (row) 与 null 进行比较。这是一个错误,因为int 永远不可能是null

    您可能想改用Integer,这是一种可以自动转换为int 的引用类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多