Word-Puzzle(ArrayList问题)

时间:2015-05-19 05:39:26

标签: java arraylist

所以我一直在创建一个Word-Puzzle,我最近陷入了一个索引出界问题。这已经解决了,但程序没有按照我的意愿去做。想法i,测试类将在数组中打印3个单词,例如[FEN,GNU,NOB](是的,他们显然是真正的英语单词)。然后检查每个单词组合的第一个字母是否是单词,依此类推,例如FGN如果是这样将它添加到下一个ArrayList,则重新开始。理想的输出例如是[FEN,GNU,NOB] [FGN,ENO,NUB]。但是当前的输出是[FEN,GNU,NOB] [SOY,SOY,SOY]或[FEN,GNU,NOB] []。

测试类



public class Test_WordPuzzleGenerator {
	public static void main(String[] args) throws FileNotFoundException {
		
		System.out.println("Test 1: size 3");
		int size = 3;
		Puzzle.WordPuzzleGenerator.generatePuzzle(size);

	}

}



 WordGenerator:


public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public static void generatePuzzle(int size) throws FileNotFoundException {
    ArrayList<String> puzzleListY = new ArrayList<String>();
    ArrayList<String> puzzleListX = new ArrayList<String>();
    String randomXWord;
    String letterSize = "" + size;
    makeLetterWordList(letterSize);
    boolean finished = false;
    while ( !finished ) {
        finished = true;
        puzzleListX.clear();
        puzzleListY.clear();
        for (int i = 0; i < size; i++) {
            int randomYWord = randomInteger(wordList.size());
            String item = wordList.get(randomYWord);
            puzzleListY.add(item);
        }
        for (int i = 0; i < puzzleListY.size(); i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < puzzleListY.size(); j++) {
                sb.append(puzzleListY.get(j).charAt(i));
            }
            randomXWord = sb.toString();
            if (!wordList.contains(randomXWord)) {
                break;
            }
            puzzleListX.add(randomXWord);
            if (puzzleListX.size() == size){
                finished = false;
            }


        }

    }
    System.out.print(puzzleListY);
    System.out.print(puzzleListX);
}

public static int randomInteger(int size) {
	Random rand = new Random();
	int randomNum = rand.nextInt(size);
	return randomNum;
}



public static void makeLetterWordList(String letterSize) throws FileNotFoundException {

	Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
	wordList.clear();
    while (letterScanner.hasNext()){
		wordList.add(letterScanner.next());
	}
	letterScanner.close();
}
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我认为你对finished变量感到困惑。将while条件替换为puzzleListX.size() != size,您的代码应该有效。