java - 从文本中导入单词

标签 java swing text hashset

我很抱歉,因为我总是问一些棘手的问题,但我真的需要帮助。无论如何,我试图将字典中仅一定长度的单词导入到作为哈希集的变量单词中。当我运行程序并尝试打印我的单词(又名字符串哈希集)时。我在控制台中没有得到任何信息,并且程序不会停止运行。我怎样才能解决这个问题?附:我还知道 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/

相关文章:

html - 网站的简单读入文件

java - 在 AChartEngine 中将堆积条形图转换为堆积 100 条形图

java - 获取 Swing GridLayout 中特定行和列的小部件

java - 有没有办法在全局范围内收听 swing 中新打开的窗口?

java - 如何将多个数组添加到 JComboBox?

jquery - 文本中的全日历去年和明年按钮

java - Android WebView使设备不稳定

java - Java 中奇怪的区分大小写问题

java - Java中的八进制转义导致错误的字节值,编码问题?

python - 如何旋转 vtkVectorText 使其面向某个方向?