![](/img/trans.png)
[英]How do I get my Hangman Java file to read a random word in from a .txt file?
[英]How to read a random word from .txt using Java JFrame
我的程序需要从包含大量单词(在不同行中)的.txt
文件中读取一个随机单词。
我能够从数组中选择一个随机单词,但我还没有找到如何从.txt
文件中读取一个随机单词。
public class GuessForm extends javax.swing.JFrame {
String[] FindWord1 = {"hello", "hey", "well", "story", "fight","punch"};
int idx = new Random().nextInt(FindWord1.length);
String FindWord = (FindWord1[idx]);
int wordL = FindWord.length();
// ...
我尝试了以下方法,但不起作用:
import java.util.Random;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner;
public class GuessForm extends javax.swing.JFrame {
String filename = "H:\\lol.txt";
File file = new File (filename);
Scanner input = new Scanner new FileReader(file));
while (input.hasNext()) {
String FindWord1 = input.next();
}
int idx = new Random().nextInt(FindWord1.length);
String FindWord = (FindWord1[idx]);
int wordL = FindWord.length();
}
如果您正在阅读许多单词,最简单的方法是将整个文件读入内存并将其存储在数组中。
如果您只检查一次,那么您可以通过只通读一次而不构建任何数据结构来节省一些时间。 请注意,它使用了大量对Random
对象的调用。
public String randomWord(String file)
{
BufferedReader reader = new BufferedReader(new FileReader(file));
int i = 1;
Random r = new Random();
String line, out;
while((line = reader.readLine()) != null)
if(r.nextDouble() < (1.0 / i++))
out = line;
return out;
}
您将需要添加一些 try/catch 或其他异常处理,但应该可以使用类似的方法
这种获取随机元素的方法主要用于 Iterators/LinkedLists/files
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.