[英]How can I display a random line from a text file?
I am new to Java and stackoverflow. 我是Java和stackoverflow的新手。 I have a text file that I wish for my Java program to read and then pick a random line and display it.
我有一个文本文件,希望Java程序读取它,然后选择一个随机行并显示它。 What I've found only demonstrates bytes and characters.
我发现的只是演示字节和字符。 How can I use strings or just a line?
如何使用字符串或仅使用一行? I apologize that this question has been asked before, but other posts have not helped me.
我很抱歉以前曾问过这个问题,但是其他帖子对我没有帮助。 I'm at a loss and I feel like there's a simple solution for this.
我很茫然,我觉得有一个简单的解决方案。
Here's what I have so far: 这是我到目前为止的内容:
package Nickname;
import java.util.Scanner;
import java.io.*;
public class Nickname {
public static void main(String[] args) throws IOException {
RandomAccessFile randomFile = new RandomAccessFile("names.txt", "r");
}
}
I suggest you use a buffered reader. 我建议您使用缓冲读取器。 With
in.readLine()
you can get your next line from the file. 使用
in.readLine()
您可以从文件中获取下一行。
Math.random()
generated a (pseudo) random number between 0 and 1. By multiplying and casting to int you generate a number between 0 and 100. If that random number happens to be of a specific value (50 in this case) you stop your loop and print the line. Math.random()
生成一个介于0和1之间的(伪)随机数。通过乘以并强制转换为int,您将生成一个介于0和100之间的数。如果该随机数恰好具有特定值(在这种情况下为50),则表示停止循环并打印行。
You can change the odds of the loop breaking by changing the multiplication factor to anything you like. 您可以通过将乘法因子更改为任意值来更改循环中断的几率。 Just make sure to compare to a number in your specified range.
只要确保与指定范围内的数字进行比较即可。
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.ready()) {
String s = in.readLine();
//1% chance to trigger, if it is never triggered by chance you will display the last line
if (((int)(Math.random*100)) == 50)
break;
}
in.close();
System.out.println(s);
Alternatively a solution like this might be more elegant and gives you an evenly distributed chance of getting either of the values: 另外,这样的解决方案可能更优雅,并为您提供平均分配的机会来获得以下两个值之一:
BufferedReader in = new BufferedReader(new FileReader(file));
List<String> myNicknames = new ArrayList<String>();
String line;
while ( (line = in.readLine()) != null) {
myNicknames.add(line);
}
in.close();
System.out.println(myNicknames.get( (int)(Math.random() * myNicknames.size()) ));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.