2012-12-06 84 views
0

我正在爲此程序編寫一個類,並且此類創建了一個對象移動到其中的板。董事會應該看起來像一個帶有「+」四角的框,「 - 」垂直和「|」一個空的中心水平會:Java toString錯誤

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

我,在另一方面,得到支架周圍的邊緣去horzontally和逗號填充中間,我不知道爲什麼:

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

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

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 
+0

〜謝謝陸for的那個改正 – user201535

+0

什麼是錯誤?嘗試改變toString()方法。 –

+0

是的,它與toString方法有關,但我似乎無法找到它。<它只是打印錯誤的字符,但我確信我有它.. – user201535

回答

2

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

當您調用Arrays.toString()方法時,它將打印一個開括號,後跟數組內容(用逗號分隔),後跟一個閉括號。

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

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

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

[1, 2, 5, 8] 

再舉一個例子,如果你有空洞填充間隙的陣列,你會得到:

[ , , , , , ] 

(查看空格?)

這就是您接收該輸出的原因。

+0

有趣,難怪!我知道如何通過訪問器方法來創建我需要的東西,但我不知道如何使用toString方法。 – user201535

+0

通過遍歷數組並將數組中的每個字符添加到一個字符串中,您可以完全避免使用'Arrays.toString()'方法。在每一行的末尾,在字符串中放置一個新行。 – apnorton

+0

好吧我得到了,public String toString(){ int i; String temp = new String(「」); String line =「」; char topBottom =' - '; int k; int row2 = theBoard [0] .length;對於(k = 0; k user201535