gpt4 book ai didi

java构造函数和clearboard方法清除棋盘除了占用的位置?

转载 作者:行者123 更新时间:2023-12-01 04:58:25 26 4
gpt4 key购买 nike

好吧,我真的需要所有这些方面的帮助,我有一个名为 Board.java 的类 棋盘被表示为二维字符数组。海龟可以通过在它经过的棋盘上的每个位置写入一个字符来留下痕迹。董事会将有两个构造函数。默认构造函数不带任何参数,并将创建一个 10 行 25 列的板。将板上的每个元素设置为空白。第二个构造函数将采用两个整数,分别指定行数和列数。如果指定的行数或列数小于 1,则将该值设置为 1。如果指定的行数或列数大于 80,则将该值设置为 80。将棋盘中的每个元素设置为空白。该类需要一个clearBoard 方法。这将在每个位置放置一个空格,除了那些被海龟占据的位置。海龟使用字符“0”、“1”、“2”、...“9”来标记它们的位置。

我已完成以下内容,但我不确定我的构造函数是否正确,并且我不知道如何启动clearBoard方法。请帮忙!!

import java.util.Arrays;

public class Board {

private char [][] theBoard;

public Board() { // This will not take any arguments


theBoard = new char [10][25]; //10 rows and 25 columns
for (int row = 0; row < theBoard.length; row++ ) {
for (int col = 0; col < theBoard[row].length; col++ )
theBoard [row][col] = ' ';
System.out.println();
}
}

public Board (int [][] theBoardArray) {
char [][] theBoard = new char [theBoardArray.length] [theBoardArray[0].length];
for (int row = 0; row < theBoard.length; row++ ) {
if (row <1)
row = 1;
else if (row >80)
row =80;
for (int col = 0; col < theBoard[row].length; col++ ){
if (col <1)
col = 1;
else if (col >80)
col =80;
theBoard [row][col] = ' ';
}
System.out.println();
}
}

最佳答案

修复了一些部分,进行了一些清理并添加了您想要的其余部分。解释在代码注释中。

public class Board {

private char [][] theBoard;

public Board() { // This will not take any arguments
this(10, 25); // calls the other constructor
// avoid duplicate code, where possible
}

// takes number of rows and collumns
public Board (int rows, int cols) {
// fix illegal row and column numbers
rows = fixNumber(rows);
cols = fixNumber(cols);
// create the board and fill it with ' '
theBoard = new char [rows][cols];
for (int row = 0; row < theBoard.length; row++) {
for (int col = 0; col < theBoard[row].length; col++)
theBoard[row][col] = ' ';
}
}

private int fixNumber(int number) {
if (number < 1) {
return 1;
} else if (number > 80) {
return 80;
} else {
return number;
}
}

// almost like constructor, just does not create a new char[][] and
// only puts ' ' into fields not containing any of '0' - '9'
public void clearBoard() {
for (int row = 0; row < theBoard.length; row++ ) {
for (int col = 0; col < theBoard[row].length; col++) {
if (theBoard[row][col] < '0' || theBoard[row][col] > '9') {
theBoard[row][col] = ' ';
}
}
}
}
}

关于java构造函数和clearboard方法清除棋盘除了占用的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13734233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com