简体   繁体   English

使用扫描仪读取文本文件并使用列表进行打印

[英]Using Scanner to read text file and print using List

This is for a homework assignment, for a game of Hangman. 这是为家庭作业分配的游戏,为Hang子手的游戏。 Now, I got the whole game working except for this part. 现在,除了这部分之外,我让整个游戏正常运行。 Reading the dictionary list that the teacher provided. 阅读老师提供的字典清单。

public static void main(String[] args) throws FileNotFoundException {

    Scanner fileScan = new Scanner(new File(words.txt));

    List<String> dictionary = new ArrayList<String>();
    while (fileScan.hasNext()) {

        dictionary.add(fileScan.nextLine().toLowerCase());
    }
    for( int i = 0; i < dictionary.size(); i++) {

        System.out.println(dictionary.get(i));
    }
}

I separated this part from the code to be able to test it. 我将这一部分与代码分离,以便能够对其进行测试。 I also made the dictionary file into just 5 words. 我还把字典文件变成了5个单词。 When I hit run, it doesn't print out anything. 当我点击运行时,它不会打印出任何内容。 Just a blank space. 只是一个空白。

words.txt must be quoted 'coz it's a string. words.txt必须加quoted ,因为它是一个字符串。

like this 像这样

 Scanner fileScan = new Scanner(new File("words.txt"));

also make sure that the file path of your txtfile is correct. 还请确保txtfile的文件路径正确。 you can use either ABSOLUTE PATH OR RELATIVE PATH 您可以使用绝对路径相对路径

when printing all the data, you can also simply do it like this using foreach 打印所有数据时,您也可以使用foreach这样简单地进行操作

for(String item:dictionary){
    System.out.println(item);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM