我目前正在尝试创建一个程序,将吐出像这样的棋盘(它在实际程序中看起来更好,只是编辑器不喜欢我使用"-"符号,所以我把它们放在引号里):
-----------------
| | | | |K| | | |
-----------------
| |P| | | |P| | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | |N| | |
-----------------
| | | | |K| | | |
-----------------
我使用两个方法,一个showBoard方法和一个addPiece方法。我目前使用的是addPiece方法,并且我正试图使该方法接受三个输入:行int、列int和字符串名称(例如,K代表king)。然而,我无法让addPiece方法把这些片段放到我想要它们去的地方,甚至根本无法做到。以下是目前为止的内容:
public class ChessBoard {
public static String[][] board = new String[8][8];
public static int row = 0;
public static int col = 0;
public static void addPiece(int x, int y, String r){
board[x][y] = new String(r);
}
public static void showBoard(){
for (row = 0; row < board.length; row++)
{
System.out.println("");
System.out.println("---------------");
for(col = 0; col < board[row].length; col++)
{
System.out.print("| ");
}
}
System.out.println("");
System.out.println("---------------");
}
public static void main(String[] args) {
System.out.println(board.length);
showBoard();
addPiece(1,2,"R");
}
}
我知道这与我编写addpiece方法的方式有关,但我仍然对如何编写该方法感到困惑,这是我最好的尝试(这不起作用)。有人有什么建议吗?谢谢!
永远不要打印片段值
for(col = 0; col < board[row].length; col++)
{
if ( board[row][col] != null ) {
System.out.print("|" + board[row][col]);
}
else
System.out.print("| ");
}
而且你还需要在展示板之前添加pience:
addPiece(1,2,"R"); //before
showBoard();
为什么使用new String(r)?您的board数组已经是字符串数组,只需使用:
board[x][y] = r;
当你在main中添加showBoard方法后的片段时,将它们切换到
addPiece(1,2,"R");
showBoard();
注意addPiece正在改变板的状态。如果你想看到改变,你需要重新显示新的板状态。
public class ChessBoard {
public static String[][] board = new String[8][8];
public static void addPiece(int x, int y, String r){
board[x][y] = r;//no need for new String(), board is already made of Strings.
}
public static void showBoard(){
//it's generally better practice to initialize loop counters in the loop themselves
for (int row = 0; row < board.length; row++)
{
System.out.println("");
System.out.println("---------------");
for(int col = 0; col < board[row].length; col++)
{
System.out.print("|"); //you're only printing spaces in the spots
if(board[column][row] == null){
System.ot.print(" ");
}else{
System.out.print(board[column][row]);
}
}
}
System.out.println("");
System.out.println("---------------");
}
public static void main(String[] args) {
System.out.println(board.length);
showBoard(); //board does not have R in it yet.
addPiece(1,2,"R"); //board now has R in it.
showBoard(); //display the new board with R in it.
}
}