1

我对编程有点陌生,需要帮助做一个递归方法。我有一个方法可以在二维数组中选择一个随机空间,然后我想检查空间是否空闲。如果空间是空闲的,我想使用它空间,但如果不是,我想在二维数组中选择一个新的随机空间。谢谢

import java.io.* ;
import java.util.ArrayList ;
public class WordSearchPuzzle
{
    private char[][] puzzle ;
    private ArrayList<String> puzzleWords ;
    private int letterCount = 0 ;
    private int gridDimensions;

    public WordSearchPuzzle(ArrayList<String> userSpecifiedWords)
    {
        this.puzzleWords = userSpecifiedWords ;

    }

    private void createPuzzleGrid()
    {
        int i, itemLength;
        String item;
        for (i = 0; i < puzzleWords.size(); i++) {
            item = puzzleWords.get(i);
            itemLength = item.length();
            letterCount = letterCount + itemLength;
        }
        gridDimensions = letterCount * 2;
        puzzle = new char[gridDimensions][gridDimensions] ;
    }

    private void generateWordSearchPuzzle()
    {

    }


    public void firstSpace(String Word) 
        {  
            int row, column;
            row = (int)(Math.random() * gridDimensions +1);
            column = (int)(Math.random() * gridDimensions +1);
            if(puzzle[row][column] != ' '){
                firstSpace();
            }
        }
4

2 回答 2

2

您在评论中提到的具体问题是因为 firstSpace 方法需要有一个字符串作为参数。你应该使用:

firstSpace(word);

另请注意,此方法当前不返回任何内容,因此您无法知道它选择了哪个空间。

于 2012-04-18T10:58:00.193 回答
0

我认为在索引计算中添加 1 是不必要的,并且可能会导致数组越界异常。虽然,这取决于您对 gridDimensions 的定义。

您在评论中指定的问题是因为 Java 编译器试图找到一个名为“void firstSpace()”的方法,这是与“void firstSpace(String word)”不同的方法。

public void firstSpace(String word) 
{  
    int row, column;

    // No need to add 1, Java arrays are accessed with the first index 
    // being 0. Math.random() returns from 0 up to but not including 1.0.
    // e.g. array size = 50, min index = 0, max index = 49
    // Lets say you get very close to 1 e.g. 0.9999, then 
    // 0.9999 * 50 = 49.995 (after integer truncating you have 49)
    row = (int)(Math.random() * gridDimensions);
    column = (int)(Math.random() * gridDimensions);

    if(puzzle[row][column] != ' ') { 
        // If this element is not "empty" then run the method again 
        // using recursion. null might be a better choice to compare
        // to depending on how you initialized the array.
        firstSpace(word);
    } else {
        // Otherwise we're finished and we can set the array element
        // to the new word.

        // (Assumed post condition (you might want to do something else once you
        // find a blank index))
        puzzle[row][column] = word;
    }
}
于 2012-04-18T11:07:41.010 回答