简体   繁体   English

从文本文件设置随机行

[英]Set random line from text file

I have a program where I want to display a random line on a label then once an action is performed, display a new one. 我有一个程序,我想在标签上显示随机行,然后在执行操作后显示一个新行。 I know how to read the contents of the file, but sure how to display a random line. 我知道如何读取文件的内容,但是确定如何显示随机行。 Also, once a line has been shown, I don't want the same line to be shown again. 另外,一旦显示了一行,我也不想再次显示同一行。 I've seen many suggestions talking about 'arrays', 'lists' and 'arraylists'. 我已经看到许多有关“数组”,“列表”和“数组列表”的建议。 I'm a bit of a novice in this area and would appreciate some help. 我在这方面是个新手,希望能有所帮助。 Thanks. 谢谢。

I've gotten this far but not sure how to do the 'random' part... 我已经走了这么远,但不确定如何做“随机”部分...

BufferedReader in = new BufferedReader(new FileReader("lines.txt"));
    String str;

    List<String> list = new ArrayList<String>();
    while((str = in.readLine()) != null){
        list.add(str);
    }

    String[] stringArr = list.toArray(new String[0]);

After the while loop, you have a list of String s where every item in the list (every String ) is one line from the file, right? 在while循环之后,您有了一个String列表,其中列表中的每个项目(每个String )都距文件一行,对吗?

So you generate a number between 0 and the length of the list to pick one String from the file, then remove that String from the list. 因此,您将生成一个介于0和列表长度之间的数字,以从文件中选择一个字符串,然后从列表中删除该字符串。

Something like 就像是

public String getRandomStringFromList(List<String> list)
{
    int index = new Random().nextInt(list.size());
    return list.remove(index);
}

(It would be better to intialize the Random once statically instead of dynamically every time you use it but this is the basis for what you want to do.) (最好是一次静态地初始化Random ,而不是每次使用它时都要动态地初始化,但这是您要做的基础。)

Also, this will not display the same line twice, unless that line is duplicated in the file. 同样,这将不会两次显示同一行,除非该行在文件中重复。 If you can have duplicate lines in the file but want to only store them once in the collection, use a Set as said in the other answer. 如果文件中可以有重复的行,但只想在集合中存储一次,则使用另一个答案中所述的Set

You can use Set instead of List. 您可以使用Set而不是List。 Then you will not have the duplicated lines. 这样就不会有重复的行。 More info, please verify here: https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html 更多信息,请在此处验证: https : //docs.oracle.com/javase/tutorial/collections/interfaces/set.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM