在这个程序中,这个用户将有机会生成自己的单词搜索。在程序开始时,将向用户显示一个指令菜单,用户可以在其中选择以下选项: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.
Ive added 'break;' in order to stop the loop, but instead I
之后的部分,我很确定它正在停止整个程序的运行。当我去掉"break;"程序不断提示我添加更多的单词(基本上直到总共添加了260个单词)。
编辑
因此,由于建议Ive received here. The program is doing what I want now, but I am getting a
NullPointerExceptionfrom my for-each loop in the
createWordSearch(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
这可能是因为您使用了answer=="N"而不是answer.equals("N").