【问题标题】:Reading a random word from a file从文件中读取随机单词
【发布时间】:2017-04-13 05:04:26
【问题描述】:

我正在学习文件读取和异常处理,我在网上找到了这个 Hangman 游戏程序的代码。有人可以在读取文件时分解for循环在程序开头的作用吗?到目前为止,我只知道读取文件并打印出文件内容的 while 循环方法。但我不确定这个人如何使用 for 循环从文件中的单词列表中读取。

代码如下:

import java.io.*;
import java.text.NumberFormat;
import java.util.*;

public class Hangman {

public static void main(String args[]) {

    try {
        Scanner scan = new Scanner(System.in);
        String fileName = "words.txt";
        Scanner fileScan = new Scanner(new File(fileName));
        ArrayList words = new ArrayList();
        String word;

        for(; fileScan.hasNext(); words.add(word)) //I am not sure what this code is doing
            word = fileScan.next();...

【问题讨论】:

  • 欢迎来到 Stack Overflow!请take the tour 了解该网站的运作方式以及此处的主题问题。另见:Why is "Can someone help me?" not an actual question?
  • 该行执行以下操作:1) 检查文件中是否有另一个单词 fileScan.hasNext() 2) 将文件中的下一个单词保存到 String 变量 @987654326 @ 在word = fileScan.next() 3) 然后它使用words.add(word) 将该字符串附加到ArrayList words。这是破解for 循环的一种奇怪方法,并且作为while 循环会更清晰。
  • 有趣!谢谢,我原以为这会比 if 语句更好,但是使用 while 循环,您不必将 word 初始化为某些东西吗?假设你的意思是while(fileScan.hasNext()) { words.add(word); word = fileScan.next(); }
  • @AustinKootz 我测试了上面的while循环,我必须初始化字符串字。
  • @janny 在 for 循环中,incrementfor( nope; nada; HERE) 最后执行,在循环体中的代码运行之后。这就是为什么我说这是一个奇怪的 hack。

标签: java for-loop random


【解决方案1】:

for 循环包含三个元素来详细说明它的行为方式:

for (<initial action>; <condition for continuing>; <action per iteration>) {
    doSomething();
}

据我所知,这三个元素都不是强制性的。像 for(;;) { &lt;body&gt; } 这样的 for 循环是非常有效的,它会永远运行,或者直到循环体中的代码达到中断条件。

在您列出的代码中:

  • &lt;initial action&gt; 为空
  • &lt;condition for continuing&gt; 是文件扫描中的单词比较多
  • &lt;action per iteration&gt;是将当前单词添加到ArrayList中

从 Java 6 (?) 开始,也有可能编写更灵活的 for 循环,其中涉及可迭代列表,如以下伪代码所示:

for (Item s : listOfItems) {
    doSomething(maybe with s);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-30
    • 2014-06-25
    • 2017-04-15
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多