简体   繁体   English

从文件中读取随机单词

[英]Reading a random word from a file

I am learning about file reading and exception handling and I found this code online for a Hangman game program. 我正在学习文件阅读和异常处理,我在网上找到了这个代码用于Hangman游戏程序。 Can someone please break down what the for loop does in the beginning of the program when reading the file? 有人可以在读取文件时分解程序开头的for循环吗? I'm so far only aware of the while loop method on reading the file and printing out whats on it. 我到目前为止只知道while循环方法读取文件并在其上打印出来。 But I am not sure how this person used a for loop to read from a list of words in a file. 但我不确定这个人是如何使用for循环从文件中的单词列表中读取的。

Here is the code: 这是代码:

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();...

A for-loop has three elements to detail how it should behave: for循环有三个元素来详细说明它应该如何表现:

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

To the best of my knowledge none of those 3 elements is compulsory. 据我所知,这三个要素中没有一个是强制性的。 A for-loop like for(;;) { <body> } is quite valid and simply runs for ever or until the code in the body of the loop reaches a break condition. 类似for(;;) { <body> }的for循环是非常有效的,并且只是运行或直到循环体中的代码达到中断条件。

In the code you listed: 在您列出的代码中:

  • the <initial action> is empty <initial action>为空
  • the <condition for continuing> is that there are more words in the filescan <condition for continuing>是文件扫描中有更多的单词
  • the <action per iteration> is to add the current word to the ArrayList <action per iteration>是将当前单词添加到ArrayList

Since Java 6 (?) there is also the possibility to write more flexible for-loops where iterable lists are concerened as in this pseudo code: 从Java 6(?)开始,还有可能编写更灵活的for循环,其中可迭代列表在此伪代码中被忽略:

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

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

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