我有一个随机数生成器和一个包含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++;
}
}
}
}
答案 0 :(得分:0)
老实说,我不知道你的代码中发生了什么,所以我写了这个就是你所描述的。 (我很无聊)
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.
}