我很抱歉,因为我总是问一些棘手的问题,但我真的需要帮助。无论如何,我试图将字典中仅一定长度的单词导入到作为哈希集的变量单词中。当我运行程序并尝试打印我的单词(又名字符串哈希集)时。我在控制台中没有得到任何信息,并且程序不会停止运行。我怎样才能解决这个问题?附:我还知道 JOptionPane 代码的一部分已经被删减得足够多了,但它没有错误,您明白了。谢谢! 亚历克斯
public void inputWords()
{
try
{
frame = new JFrame("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
input = new Scanner(new FileInputStream("dictionary.txt"));
wordLength = Integer.parseInt( JOptionPane.showInputDialog(null,
String importedWords = input.nextLine();
while(stillHasWords==true)
{
if(importedWords.length()==wordLength)
{
words.add(importedWords);
}
else
{
}
}
}
catch(FileNotFoundException f)
{
System.out.println("File does not exist.");
System.exit(0);
}
catch(NoSuchElementException q)
{
stillHasWords=false;
}
public static void main(String[] args)
{
EvilHangman j = new EvilHangman();
System.out.println(stillHasWords);
j.inputWords();
System.out.println(words + " ");
}
}
最佳答案
关于:
while(stillHasWords==true)
{
if(importedWords.length()==wordLength)
{
words.add(importedWords);
}
else
{
}
}
我不确定 Words.add(importedWords) 的作用,但对于您遇到的问题最重要,
问题:您在循环内的哪里更改 stillHasWords ?
答案:你不这样做,所以循环永远不会结束。
我建议你首先修复这个 while 循环
顺便说一句,最好避免在 while 循环中使用 == true ,而只是测试 boolean 值:
while (stillHasWords) {
// add a word
// change stillHasWords to false if we've run out of words
}
编辑
您声明:
Still has words changes in the catch(NoSuchElementException q)
在 while 循环内部没有发布 catch block ,因此我认为根据您迄今为止发布的代码,stillHasWords 值仍然无法在 while 循环内部更改 。如果您有更相关的代码,那么您当然会想要显示它,否则我们只能猜测未显示的代码可能有什么问题。最好发个SSCCE
关于java - 从文本中导入单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18220135/