我想将字符串拼图转换为二维字符数组,就像一个字拼图。这是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;
}
}
我可以建议用较小的输入来编写测试 - 比如2x2或3x3。比起这些“随机”字母来说,理解起来要容易得多。 –
测试不是由我写的,它是给出的。不过谢谢。 –