我想将 String puzzle 转换为 2D Char Array,就像 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;
}
}
最佳答案
puzzleArray 的初始化器:
private char [][] puzzleArray = new char[numRows][numRows];
在构造函数之前调用,此时numRows
为零,因此puzzleArray.length == 0
。
只需将 puzzleArray = new char[numRows][numRows];
移至构造函数即可。
关于java - Java 中从字符串到二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32889428/