我目前正在高中的HangmanProject工作。 “newWord”是包含随机在字典文件中选择的单词的变量。在makeList方法中,您可以看到它随机拉出单词。还有一个System.out.println(“this:”+ newWord);所以我可以测试一下这个单词是否从外部文件中成功拉出。然后它返回newWord,但是当返回main方法时,它是空的,因此在整个程序的其余部分都是空的。有人可以帮我解决问题吗?
public class HangmanProject {
public static void main(String args[]) {
String newWord = " ";
int letterNumber = 0;
makeList(newWord);
countLetters(newWord, letterNumber);
System.out.println("this: " + newWord);
displayBoard(letterNumber, newWord);
}
public static String makeList(String newWord) {
do{
try(Scanner s = new Scanner(new File("dictionary.txt"))) {
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()) {
list.add(s.next());
}
Random random = new Random();
int index = random.nextInt(list.size());
newWord = list.get(index);
} catch (IOException e) {
System.out.println("Error Found");
}
} while (!(newWord.length() >= 5));
System.out.println("this: " + newWord);
return newWord;
}
答案 0 :(得分:1)
您不会对返回的值执行任何操作。只需将它分配到某个地方就可以了。此外,由于makeList
不使用其值,因此只需将其声明为局部变量:
String newWord = makeList();