簡體   English   中英

Java toString錯誤

[英]Java toString error

我正在嘗試為這個程序編寫一個類,這個類創建了一個對象移動的板。該板應該看起來像四個角上帶有“+”的盒子,“ - ”垂直移動並且“|” 與空中心水平走:

+-----+
|     |
|     |
|     |
|     |
+-----+

另一方面,我得到括號圍繞邊緣,以及填充中間的逗號,我不知道為什么:

[ , , , , ] 
[ , , , , ]
[ , , , , ] 
[ , , , , ] 
[ , , , , ] 

我的課程是對的,但我需要幫助我的班級。

import java.util.Arrays;
import java.util.Random;

public class Board {

    private char [][] theBoard;

    public Board() { 
        this(10, 25); 
    }


    public Board (int rows, int cols) {
        if (rows < 1 || rows>80) {
            rows = 1;
        }
        if (cols<1 || cols > 80) {
            cols = 1;
        }
        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] = ' ';
    }
    }

        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] = ' ';   
    }
    }
    }
    }

            public void setRowColumn(int row, int col, char character) {
           theBoard[row][col] = character;
        }

            public char getRowColumn(int row, int col) {
            return theBoard[row][col];
        }

        public String toString() {
    StringBuilder strb = new StringBuilder();
    for (char[] chars : theBoard) {
        strb.append(Arrays.toString(chars) + "\n");
    }
    return strb.toString();
    }
    public static void main(String [] args)
   {
      Board aBoard, anotherBoard;

      System.out.println("Testing default Constructor\n");
      System.out.println("10 x 25 empty board:");

      aBoard = new Board();
      System.out.println(aBoard.toString());

      System.out.println();

      // And, do it again
      System.out.println("Testing default Constructor again\n");
      System.out.println("10 x 25 empty board:");

      anotherBoard = new Board();
      System.out.println(anotherBoard.toString());

   } // end of method main
} // end of class 

默認構造函數使用空格填充數組: ' '

當您調用Arrays.toString()方法時,它會打印一個開括號,跟隨數組的內容(用逗號分隔),然后是一個閉括號。

例如,如果您有一個數組:

i  a[i]
0   1
1   2
3   5
4   8

調用Arrays.toString(a)打印出來:

[1, 2, 5, 8]

再舉一個例子,如果你有一個填充空格的數組,你會得到:

[ ,  ,  ,  ,  , ]

(見空格?)

這就是你收到輸出的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM