2015-10-01 136 views
1

我想将字符串拼图转换为二维字符数组,就像一个字拼图。这是TestClass中的一部分:从字符串到Java中的二维字符数组

public class WordPuzzleTest { 

WordPuzzle myPuzzle = null; 

/** 
* This function will initialize the myPuzzle variable before you start a new test method 
* @throws Exception 
*/ 
@Before 
public void setUp() { 
    try { 
     this.myPuzzle = new WordPuzzle("VNYBKGSRORANGEETRNXWPLAEALKAPMHNWMRPOCAXBGATNOMEL", 7); 
    } catch (IllegalArgumentException ex) { 
      System.out.println("An exception has occured"); 
      System.out.println(ex.getMessage()); 
    } 

} 

/** 
* Test the constructor of the {@link WordPuzzle} class 
*/ 
@Test 
public void testWordPuzzle() { 
     assertNotNull("The object failed to initialize", this.myPuzzle); 
     char[][] expectedArray = {{'V','N','Y','B','K','G','S'}, 
           {'R','O','R','A','N','G','E'}, 
           {'E','T','R','N','X','W','P'}, 
           {'L','A','E','A','L','K','A'}, 
           {'P','M','H','N','W','M','R'}, 
           {'P','O','C','A','X','B','G'}, 
           {'A','T','N','O','M','E','L'}}; 
     assertArrayEquals(expectedArray, this.myPuzzle.getLetterArray()); 
} 

以下是我写这样做的代码,但我得到这个错误:java.lang.ArrayIndexOutOfBoundsException:0

我不知道为什么,这将无法工作,但我很可能犯了一个愚蠢的错误。任何想法?

public class WordPuzzle { 

    private String puzzle; 
    private int numRows; 
    private char [][] puzzleArray = new char[numRows][numRows]; 

    public WordPuzzle(String puzzle, int numRows) { 
     super(); 
     this.puzzle = puzzle; 
     this.numRows = numRows; 

     char[] puzzleChar; 
     puzzleChar=puzzle.toCharArray(); 

     int index=0; 
     int i=0; 
     int j=0; 
     while (i<numRows) { 
      while (j<numRows) { 
       puzzleArray[i][j] = puzzleChar[index]; 
       j++; 
       index++; 
      } 
      i++; 
      j=0; 
     } 
    } 
+0

我可以建议用较小的输入来编写测试 - 比如2x2或3x3。比起这些“随机”字母来说,理解起来要容易得多。 –

+0

测试不是由我写的,它是给出的。不过谢谢。 –

回答

0

puzzleArray的初始化:

private char [][] puzzleArray = new char[numRows][numRows]; 

的构造函数之前被调用,当numRows为零,因此puzzleArray.length == 0

只需将puzzleArray = new char[numRows][numRows];移动到构造函数。

0
private int numRows; 
private char [][] puzzleArray = new char[numRows][numRows]; 

可能是这个原因。 第一行是一个int,但没有定义一个值,因此该值变为0. 第二行创建一个大小为numRows x numRows的数组,因此0 x 0. 我想那不是你想要的。

相关问题