使用扫描仪读取文本文件并使用列表打印
Using Scanner to read text file and print using List
这是一项家庭作业,一个 Hangman 游戏。现在,除了这部分,我让整个游戏都能正常工作。阅读老师提供的字典表。
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));
}
}
我将这部分从代码中分离出来以便能够对其进行测试。我还把字典文件做成只有 5 个单词。当我点击 运行 时,它没有打印出任何内容。只是一个空白 space。
words.txt
必须是 quoted
因为它是一个字符串。
像这样
Scanner fileScan = new Scanner(new File("words.txt"));
还要确保您的 txt 文件的文件路径是正确的。您可以使用 ABSOLUTE PATH OR RELATIVE PATH
当打印所有数据时,你也可以简单地使用foreach
for(String item:dictionary){
System.out.println(item);
}
这是一项家庭作业,一个 Hangman 游戏。现在,除了这部分,我让整个游戏都能正常工作。阅读老师提供的字典表。
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));
}
}
我将这部分从代码中分离出来以便能够对其进行测试。我还把字典文件做成只有 5 个单词。当我点击 运行 时,它没有打印出任何内容。只是一个空白 space。
words.txt
必须是 quoted
因为它是一个字符串。
像这样
Scanner fileScan = new Scanner(new File("words.txt"));
还要确保您的 txt 文件的文件路径是正确的。您可以使用 ABSOLUTE PATH OR RELATIVE PATH
当打印所有数据时,你也可以简单地使用foreach
for(String item:dictionary){
System.out.println(item);
}