java - Java 中从字符串到二维字符数组

标签 java arrays string char

我想将 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/

相关文章:

java - 翻译硬编码字符串的最佳实践

java - 即使具有 ArrayList 中的值,带有 TextView 的动态 TableLayout 也是空的

java - 如何将依赖项打包到输出 jar 中?

c - 如何从C函数中返回字符数组

java - 获取strings.xml中的所有字符串

java - 带 String.split() 的正则表达式

字符串 CONSTRAINT_ERROR 长度检查失败

java - ANTLR 基本行为

python - 高效的 numpy.cumsum 和 numpy.digitize

python - 使用 numpy 获取 3D 空间中所有对象的相对位置