我想将字符串拼图转换为2D字符数组,就像wordpuzzle一样。这是测试类的一部分:
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 :(得分:0)
number = Trim(Left(number , Len(number ) - 1))
的初始化程序:
puzzleArray
当private char [][] puzzleArray = new char[numRows][numRows];
为零时,在构造函数之前调用,因此numRows
。
将puzzleArray.length == 0
移至构造函数。
答案 1 :(得分:0)
private int numRows;
private char [][] puzzleArray = new char[numRows][numRows];
可能是这个原因。 第一行是int,但没有定义值,因此该值变为0。 第二行创建一个数组,其大小为numRows x numRows,因此为0 x 0。 我猜这不是你想要的。