[英]In java, how do I tell a file to choose and print a random word?
以下是我到目前为止的代码。 我几周前才开始编程,所以我对这一切都是新手,我不知道如何随机 select 并打印一个单词。 我从哪说起呢?
public static String randomWord(String fileName)
throws FileNotFoundException {
int fileSize = countWords(fileName);
int N = (int) (fileSize*Math.random());
Scanner inFile = new Scanner(new File(fileName));
String word;
while (inFile.hasNext()) {
word = inFile.next();
}
inFile.close();
return word;
}
您好,看来您的变量N
是您要查找的随机单词的编号位置(另外,与您的问题不同,但在 java 中,所有变量名称都以小写字母开头是很常见的,使用camelCase )。 有几种方法可以做到这一点,您可以使用 while 循环,您必须将文件中的每个单词放入一个数组中,如果您想稍后获取其他随机单词,这将很有用,或者您可以只跟踪你在循环本身中的编号单词,并在你到达它时打印第 N 个单词。 像这样:
int fileSize = countWords(fileName);
int N = (int) (fileSize*Math.random());
Scanner inFile = new Scanner(new File(fileName));
int count = 0;
while(inFile.hasNext() && count < N) {
inFile.next();
count ++;
}
String word = inFile.next();
System.out.println(word);
您可以通过这种方式生成随机数
import java.util.Random;
Random rand = new Random();
int rand_int = rand.nextInt(1000);
System.out.println("Random Integers: "+rand_int);
使用随机 Integer 选择随机词作为阅读器中的文件索引。 希望它会奏效
[注意]:此方案适合练习目的,但在时空权衡方面代价高昂,如果您要向月球发射火箭,请不要复制粘贴此代码!
对于更简单的解决方案,您可以将这些单词一一添加到 ArrayList 中,然后您可以返回一个随机索引。
这是示例代码:
public static String randomWord(String fileName)
throws FileNotFoundException {
Scanner inFile = new Scanner(new File(fileName));
ArraList<String> arr = new ArraList<String>();
String word;
while (inFile.hasNext()) {
word = inFile.next();
arr.add(word);
}
inFile.close();
Random rand = new Random(); //instance of random class
int upperbound = arr.size();
//generate random values from 0-(N-1)
int int_random = rand.nextInt(upperbound);
return arr.get(int_random);
}
我还没有编译它,但如果你在执行它时遇到任何错误,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.