0

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]);
wj381
  • 57
  • 5
  • 4
    Can you post some code of what you have tired? – BadSkillz Jul 29 '15 at 08:43
  • what you could do is make 2 lists[just like your stringArr. One where you keep all the lines of the file and one where you keep the already used/selected lines.For selecting random stuff you could consult this link: http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java – tudoricc Jul 29 '15 at 08:54

2 Answers2

1

After the while loop, you have a list of Strings where every item in the list (every String) is one line from the file, right?

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.

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.)

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.

Buurman
  • 1,914
  • 17
  • 26
0

You can use Set instead of List. Then you will not have the duplicated lines. More info, please verify here: https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html

Kenny Tai Huynh
  • 1,464
  • 2
  • 11
  • 23