首页 > 解决方案 > 获取词搜索生成器的词输入列表

问题描述

在这个程序中,该用户将有机会生成自己的单词搜索。在程序开始时,用户将看到一个指令菜单,他们可以在其中选择以下选项: 1. 创建单词搜索 2. 打印单词搜索 3. 查看单词搜索的解决方案 4. 退出程序

在选择创建单词搜索时,会要求用户逐行输入他们选择的单词。这些单词将存储在一维数组中。

用户必须输入最少 20 个词,最多 260 个。每批输入 20 个词,系统会询问用户是否要添加更多词。如果用户选择添加更多单词,程序将提示他/她输入更多单词,直到达到最大单词数。

如果他们选择停止添加更多单词,程序将直接将一维数组转换为数组列表,然后创建单词搜索,这就是我遇到的小问题。

if (choice == 1) {

    System.out.println("Enter words of your choice line-by-line. You can enter a maximum of 260 words (i.e., 10 words per letter)");    

    System.out.println("");

    String[] wordList = new String[260];

    // This for loop will loop around with it`s body the user decides they have added enough words and wish to proceed

    for (int i = 0; i < wordList.length; i++) {

        wordList[i] = input.nextLine();

          if (wordList[i] == wordList[19] || wordList[i] == wordList[39] || wordList[i] == wordList[59] || wordList[i] == wordList[79] || wordList[i] == wordList[99] || wordList[i] == wordList[119]|| wordList[i] == wordList[139]) {

         System.out.print("Do you want to keep adding words? Enter Y/N: ");
                  String answer = input.next().toUpperCase();

               if (answer == "Y") {

                    wordList[i] = input.nextLine();

               } if (answer == "N") {

                    break;

                 }//end of inner if

               }//end of outer if

            }//end of for loop

        List<String> words = Arrays.asList(wordList);

        createWordSearch(words);

当用户输入“N”时,程序应该结束 for 循环并在}//end of for loop.ve added 'break;' in order to stop the loop, but instead I很确定它会阻止整个程序继续运行后直接跳转到该部分。当我删除'break;' 该程序不断提示我添加更多单词(基本上直到总共添加了 260 个单词)。

编辑

ve received here. The program is doing what I want now, but I am getting a因此,感谢我NullPointerException from my for-each loop in thecreateWordSearch(words)` 方法的建议,我已经解决了那里的问题。

public static WordArray createWordSearch(List<String> words){
    WordArray wordArr = new WordArray();    
    // Have numAttempts set to 0 because the while loop below will add one every time we create a new word search       
    int numAttempts = 0;        
    while (++numAttempts < 100) { // There will be 100 attempts to generate our word array/grid     
        Collections.shuffle(words); // The words will be shuffled/randomized            
        int messageLength = placeMessage(wordArr, "Word Search Puzzle");            
        int target = arraySize - messageLength;         
        int cellsFilled = 0;            
        for (String word : words) { // For each word in the array list 'words'...               
            cellsFilled += placeWord(wordArr, word); // NULL POINTER EXCEPTION!!! 'word' is not initialized I`m pretty sure

标签: javaarraysnullpointerexceptionuser-input

解决方案


这可能是因为您确实回答了 == "N" 而不是 answer.equals("N")。


推荐阅读