java - 从文件中读取一个随机单词供用户猜测 - Java
问题描述
我正在编写一个从文件中提取一个单词并猜测它的代码。例如,这个词是“苹果”。
用户将看到: *****
如果他们输入“p”作为猜测,他们会看到:*pp**
到目前为止,如果我在一个名为 secretPhrase 的变量中手动输入单词 apple,它就可以工作,但是我不确定如何让程序从文本文件中提取单词并将其存储到 secretPhrase 中以供用户猜测。
public static void main(String args[]) {
String secretPhrase = "apple";
String guesses = " ";
Scanner keyboard = new Scanner(System.in);
boolean notDone = true;
Scanner word = new Scanner(System.in);
System.out.print("Enter a word: ");
while(true) {
notDone = false;
for(char secretLetter : secretPhrase.toCharArray()) {
if(guesses.indexOf(secretLetter) == -1) {
System.out.print('*');
notDone = true;
} else {
System.out.print(secretLetter);
}
}
if(!notDone) {
break;
}
System.out.print("\nEnter your letter:");
String letter = keyboard.next();
guesses += letter;
}
System.out.println("Congrats");
}
解决方案
你有几个选择。一是做到以下几点。它不完整,不检查边境案件。但你可以弄清楚。它假定文件每行包含一个单词。
try {
RandomAccessFile raf = new RandomAccessFile(
new File("wordfile.txt"), "r");
Random r = new Random();
// ensure the length is an int
int len = (int)(raf.length()&0x7FFFFFFF);
// randomly select a location
long loc = r.nextInt(len);
// go to that file location
raf.seek(loc);
// find start of next line
byte c = raf.readByte();
while((char)c != '\n') {
c = raf.readByte();
}
// read the line
String line = raf.readLine();
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
}
对于一组较小的单词,一个更简单的解决方案是将它们读入 aList<String>
并执行 aCollections.shuffle()
以随机化它们。然后按打乱顺序使用它们。
推荐阅读
- flutter - 在毫秒时代 Flutter 中转换时间戳
- node.js - 如何测试节点服务的“FormData”请求?
- python - 在尝试搜索特定文本时卡在“while”循环中
- api-key - Guidewire InsuranceSuite 10 在进行 API 调用时可以使用自定义标头吗?
- database - watermelonDb:如何在模式中将字符串数组作为列类型传递?
- javascript - 用 JS 关闭 py 终端
- c# - 事件在错误的按钮上触发
- cypress - 在 Cypress 中重载自定义命令
- php - 当帖子分配给多个时,如何仅显示特定分配的类别
- python - Factoranalyzer 使用 Python 3.5 和 Python 3.7 计算不同的分数