创建两个方法,返回布尔方法?

时间:2013-03-12 15:05:54

标签: java

我只是想知道我是否能对我的程序有所帮​​助,这些要求:

现在添加两个公共方法来获取和设置这个新数组的值: public void uncover(int thisCol,int thisRow)uncovermethod将指定方块的状态更改为false。否则,如果输入坐标位于雷区之外或方形已经被揭开,则它什么都不做。

public boolean isCovered(int thisCol,int thisRow)如果覆盖了指定的正方形,则isCoveredmethod返回true。否则,如果输入坐标位于雷区之外或者方括号未被覆盖,则返回false。

我尝试在下面创建这些方法,但我不认为它们是正确的,请任何人都可以看看吗?

public void uncover(int thisCol, int thisRow) {
    if(thisCol <0 || thisRow < 0)
        return null;
    if(thisCol>=numCols || thisRow>=numRows)
        return null;
}

public boolean isCovered(int thisCol, int thisRow){
    if(thisCol >0 || thisRow > 0)
        return true;
    if(thisCol>=numCols || thisRow>=numRows)
        return true;
    else;
        return null;
}

3 个答案:

答案 0 :(得分:0)

第一种方法: -

public void uncover(int thisCol, int thisRow)

这是一种无效方法。这意味着您无法返回任何值(null, true or false)

第二种方法: -

public boolean isCovered(int thisCol, int thisRow)

您不能返回null,因为返回类型是布尔值。所以它应该是return false;

以上更改需要更正。之后您可以尝试使用您的代码。

答案 1 :(得分:0)

我的理解(在C#中)是“public void”表示你没有向调用者返回任何内容。所以在“揭开”方法中,我希望它在尝试返回Null时会给你一个错误。

另外,在第二个上,我希望在“返回null”行上也会看到一个错误,因为你的返回类型是布尔值。

答案 2 :(得分:0)

假设数组是在变量中的类中声明的:

private boolean thisArray[][];

这是正确的uncover函数:

public void uncover(int thisCol, int thisRow) {
    if(thisCol < 0 || thisRow < 0) return;
    if(thisCol >= numCols || thisRow >= numRows) return;
    thisArray[thisCol][thisRow] = true;
}

更正:

  1. 返回没有值的语句,因为函数返回void
  2. 最后一行中数组值的分配:thisArray[thisCol][thisRow] = true
  3. 这是正确的isCovered函数:

    public boolean isCovered(int thisCol, int thisRow){
        if(thisCol < 0) return false;
        if(thisRow < 0) return false;
        if(thisCol >= numCols) return false;
        if(thisRow >= numRows) return false;
        return thisArray[thisCol][thisRow];
    }
    

    更正:

    1. 如果坐标位于正方形之外,则必须返回false,您正在返回true;
    2. 您错过了检查我在最后一行添加的数组的有效值:return thisArray[thisCol][thisRow];