Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从文件中读取随机字_Java_For Loop_Random - Fatal编程技术网

Java 从文件中读取随机字

Java 从文件中读取随机字,java,for-loop,random,Java,For Loop,Random,我正在学习文件读取和异常处理,我在网上找到了一个Hangman游戏程序的代码。在读取文件时,是否有人可以分解for循环在程序开始时所做的工作?到目前为止,我只知道while循环方法读取文件并打印出文件上的内容。但我不知道这个人是如何使用for循环来读取文件中的单词列表的 代码如下: import java.io.*; import java.text.NumberFormat; import java.util.*; public class Hangman { public static

我正在学习文件读取和异常处理,我在网上找到了一个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();...

for循环有三个元素来详细说明其行为:

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

for循环有三个元素来详细说明其行为:

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

欢迎来到堆栈溢出!请看看这个网站是如何运作的,这里有什么问题。另请参见:该行执行以下操作:1)检查文件
fileScan.hasNext()
2)将文件中的下一个单词保存到
String
变量
word
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循环中,最后执行
增量
,即
for(nope;nada;HERE)
,在循环体中的代码运行之后。这就是为什么我说这是一个奇怪的黑客。欢迎来到堆栈溢出!请看看这个网站是如何运作的,这里有什么问题。另请参见:该行执行以下操作:1)检查文件
fileScan.hasNext()
2)将文件中的下一个单词保存到
String
变量
word
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循环中,最后执行
增量
,即
for(nope;nada;HERE)
,在循环体中的代码运行之后。这就是为什么我说这是一个奇怪的黑客。