【问题标题】:From String to 2D Char Array in JavaJava中从字符串到二维字符数组
【发布时间】:2015-10-01 13:54:45
【问题描述】:

我想将字符串拼图转换为 2D 字符数组,就像文字拼图一样。这是测试类的一部分:

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。它比这个巨大的“随机”字母更容易理解。
  • 测试不是我写的,是给的。不过还是谢谢。

标签: java arrays string char


【解决方案1】:

puzzleArray 的初始化器:

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

在构造函数之前调用,当numRows为零时,所以puzzleArray.length == 0

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

【讨论】:

    【解决方案2】:
    private int numRows;
    private char [][] puzzleArray = new char[numRows][numRows];
    

    可能是这个原因。 第一行初始化一个int,但没有定义值,所以值变成了0。 第二行创建一个数组,大小为 numRows x numRows,因此为 0 x 0。 我猜这不是你想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-12
      • 2013-11-30
      • 2013-10-10
      • 2010-12-19
      • 2019-09-14
      • 2016-02-15
      • 2019-02-18
      • 2018-07-24
      相关资源
      最近更新 更多