Java 如何将txt文件中的单词列表分配给rng可以选择的数字?

Java 如何将txt文件中的单词列表分配给rng可以选择的数字?,java,Java,我有一个随机数生成器和一个包含50个状态的txt文档,还有一个读取列表的扫描仪,如何让我的程序打印出一个随机选择的状态,而不是一个随机数量的状态列表 这是一个课堂项目,我使用了不同的程序 import java.util.*; import java.io.*; /** This is intended as a starter for a word scrambler (anagram generator) that scrambles a randomly selected wo

我有一个随机数生成器和一个包含50个状态的txt文档,还有一个读取列表的扫描仪,如何让我的程序打印出一个随机选择的状态,而不是一个随机数量的状态列表

这是一个课堂项目,我使用了不同的程序

import java.util.*;

import java.io.*;



/**

This is intended as a starter for a word scrambler (anagram generator)

that scrambles a randomly selected word from a word file specified on the

command line.



 This program simply echos the entire contents of the file to the console.

 It assumes that the first line of the input contains the number of words in     the file

 (not including the count if you think of it as a word). 

 For this program, a word is any white space delimited sequence of characters.

 @author Charlie McDowell (minor mods Dean Bailey 08/23/07)
*/

    class Echo {

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

        Scanner in = new Scanner(new FileInputStream(args[0]));

        Random rng = new Random();
        int rnum, j;
        for (j = 1; j <= 1; j++) {
            rnum = rng.nextInt(50);

            int size = in.nextInt();//first item is the number of words

            int i = 0;//changed value of "i" to the random number that is generated

            while (i++ < rnum) {
                if (i == rnum) ;
                System.out.println();
                i++;
            }
        }
    }
}

老实说,我不知道你的代码中发生了什么,所以我写了这个,它符合你的描述。我很无聊

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

    Scanner in = new Scanner(new FileInputStream(args[0]));
    Random rng = new Random();

    int size = in.nextInt();                    //Read the first line for the number of words
    in.nextLine();                              //Because nextInt doesn't move to the next line, and the for loop has to start on the first line with something on it.
    String[] lines = new String[size];          //Create an array of Strings to hold the words

    for(int i=0; i<size; i++){                  //Read in the lines from the file into the array
        lines[i] = in.nextLine();
    }

    System.out.println(lines[rng.nextInt(size)]);       //Pick a random index from the array and display it. This can be put in a loop if multiple outputs are required.

                                                //THIS IS NOT FAULT TOLERANT; IF THE FILE CONTAINS FEWER LINES THAN ARE SPECIFIED IN THE FIRST LINE, AN ERROR WILL BE THROWN.


}

您的for循环不循环。此处没有足够的内容可供评论。你的println什么都不做。while循环在随机数目的值上循环。再试一次。这不是一个完成的代码。这是一个实验,它有一些零件是我在事故中弄坏的。谢谢你的评论。谢谢,我会研究这一点,并对我的代码进行适当的调整。