[英]Using a 2D arraylist to create a chessboard and pieces
我當前正在嘗試創建一個這樣的程序,以吐出這樣的棋盤(在實際程序中看起來更好,只是對於編輯器,我不喜歡使用“-”符號,因此將其放在引號中):
-----------------
| | | | |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("| ");
}
而且,在展示木板之前,您還需要添加虔誠的心:
addPiece(1,2,"R"); //before
showBoard();
為什么要使用新的String(r)? 您的電路板數組已經是字符串數組,只需使用:
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.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.