![](/img/trans.png)
[英]How do you print a specific line of text from a text file using math.random in Java?
[英]Print random line from text file in java
我是 Java 新手,对于一个班级,我应该创建一个刽子手风格的游戏。 首先,我只是想从 txt 文件中提取一个随机单词,但是当我运行以下代码时,它只会打印完整列表。 有什么建议? 我的老师建议我们不能使用数组,我们必须获得一个随机整数,然后将它与 nextLine 一起使用以获取随机词...
另外,忽略随机声明的变量,这在分配的后面,但不要问这个,除非以后需要!
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class WordGame {
static Random randomNum = new Random();
public static void main(String[] args) throws IOException
{
int numberGames = 1;
int highScore;
int avgScoreRunning;
int avgScoreFinal;
int currentScore;
String secretWordFinal = "";
System.out.print("Welcome to Words: The Word Guessing Game!\n");
System.out.print("Play as many games as you like. I'll remember your top score.\n");
System.out.println("and also compute your average for all games played.");
findWord(secretWordFinal);
}
public static void findWord(String secret) throws IOException
{
File wordList = new File("wordlist.txt");
Scanner wordListNew = new Scanner(wordList);
int wordNumber = randomNum.nextInt(33735) +1;
for(int i = 1; i <= wordNumber;){
if(i < wordNumber){
i++;
}
else if (i == wordNumber){
String secretWord = wordListNew.nextLine();
System.out.println(secretWord);
}
答案归结为您的for
循环条件以及您何时调用nextLine()
。
从nextLine()
,您目前只在到达所需编号的行时调用nextLine()
。 但是,您还需要将文件中的“指针”前移以到达该行,否则,您在调用它时只会读取文件的第一行。 但是,这与下一个问题复杂化:
其次,因为你for
循环条件是i <= wordNumber
,你是继续循环,当你终于得到该行号,但因为你不增加i
,一旦你达到你想要的数字再次(你没有i++
在你的else if
代码中),它总是计算为真( i == wordNumber
)并保持循环。 您可以在下面看到我将i
的增量放入for
循环的第三个位置,以便它始终增量。
for(int i = 1; i <= wordNumber; i++){
String secretWord = wordListNew.nextLine();
if (i == wordNumber){
System.out.println(secretWord);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.