我是一个新手编程,需要帮助做一个递归方法。我有一个方法,在二维数组中选择一个随机空间,然后我想检查空间是否空闲。如果空间是免费的,我想要使用该空间,但如果不是,我想在2d数组中选择一个新的随机空间。谢谢
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();
}
}
答案 0 :(得分:2)
您在评论中提到的具体问题是因为firstSpace方法需要将字符串作为参数。你应该使用:
firstSpace(word);
另请注意,此方法目前不返回任何内容,因此您无法知道它选择了哪个空格。
答案 1 :(得分: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;
}
}