0

我试图在二维数组中包含一个字符,问题是,当我为元素编写位置时,代码似乎忽略了它,默认情况下位置为 0、0。这是该方法的代码:

public boolean placePiece(int row, int col, char piece)
{
    setPos(x, y);
    setPiece(piece);
    if (piece != 'K' && piece != 'C')
        return false;   
    else {
        board[x][y] = piece;
        return true;
    }
}

方法 setPos() 的代码

private void setPos(int x, int y)
{
    this.x = x;
    this.y = y;

    if (x >= size && y >= size)
    {
        System.out.println("Out of range.");
    }


}

除了正在发生的奇怪事情之外,我在执行另一种方法时也会出现无限循环。此方法计算所选行中的所有“K”并将结果打印给用户。

    this.line = line;
    this.number = number;
    int counter = 0;
    if (line == 'r' || line == 'R')
        for (int j = 0; j < size; j++) {
            while (board[number][j] == 'K')
            {
                counter += 1;
                System.out.println("You've found " + counter + " keys!");
            }
            if (board[number][j] != 'K')
            {
                System.out.println("Try again, you haven't found any key yet.");
            }
        }

不知道如何摆脱 while 并引入另一种结构。

希望你能帮助我,提前问候和感谢!

4

1 回答 1

0

替换whileif

for (int j = 0; j < size; j++) {
   if( board[number][j] == 'K') {
      ++counter;
   }
}
System.out.println("You've found " + counter + " keys!");
于 2013-02-16T21:55:31.523 回答