我目前正在尝试创建一个会像这样的棋盘吐出的程序(它在实际程序中看起来更好,只是编辑器不喜欢我使用“ - ”符号所以我把它们放在引号中引号):
-----------------
| | | | |K| | | |
-----------------
| |P| | | |P| | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | |N| | |
-----------------
| | | | |K| | | |
-----------------
我正在使用两种方法,一种是showBoard方法,另一种是addPiece方法。我目前仍然坚持使用addPiece方法,并且我正在努力使它因此该方法需要三个输入:行int,列int和字符串名称(例如,对于King来说只是K)。但是,我无法通过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方法的方式有关,但我仍然对编写方法应该是多么困惑,这是我最好的尝试(不起作用)。有没有人有什么建议?谢谢!
答案 0 :(得分:2)
您永远不会打印件值
for(col = 0; col < board[row].length; col++)
{
if ( board[row][col] != null ) {
System.out.print("|" + board[row][col]);
}
else
System.out.print("| ");
}
在展示董事会之前,你还需要增加一些时间:
addPiece(1,2,"R"); //before
showBoard();
答案 1 :(得分:1)
为什么使用新的String(r)?你的board数组已经是一个字符串数组,只需使用:
board[x][y] = r;
此外,您正在主要的showBoard方法之后添加该片段,切换它们
addPiece(1,2,"R");
showBoard();
答案 2 :(得分:1)
请注意,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.
}
}