Vitalij Kornijenko
Vitalij Kornijenko

Reputation: 559

Random line select from a file

I'm trying to make a method that a random line from lol.txt (which has 113 lines) would be chosen and sent out as message box. How it should work:

  1. Generates random number from 0 till 112
  2. a for loop should go over the random number of lines
  3. output the randomly generated line as a message box

In my case step 2 doesn't work so I was hoping that someone could suggest on that. Here's the code:

public void close(){
    try{
        Random random = new Random();
        int randomInt = random.nextInt(112);
        FileReader fr = new FileReader("lol.txt");
        BufferedReader reader = new BufferedReader(fr);
        String line = reader.readLine();
        Scanner scan = null;
        for (int i = 0; i < randomInt + 1; i++) {
            scan = new Scanner(line);
            line = scan.nextLine();
        }
        JOptionPane.showMessageDialog(null,line);
    }catch (IOException e){
        JOptionPane.showMessageDialog(null,e.getMessage()+" for lol.txt","File Error",JOptionPane.ERROR_MESSAGE);
    }
}

If you want to send me the solution with an array list that's fine but I would really like it to be how I planned it initially.

Upvotes: 1

Views: 9274

Answers (2)

Mark M
Mark M

Reputation: 1600

It's best to use a list for this purpose, as well as make the random size dynamic to adjust to the size of your file. In case you wanted to add more lines without having to change code.

BufferedReader reader = new BufferedReader(new FileReader("lol.txt"));
String line = reader.readLine();
List<String> lines = new ArrayList<String>();
while (line != null) {
     lines.add(line);
     line = reader.readLine();
}
Random r = new Random();
String randomLine = lines.get(r.nextInt(lines.size()));
JOptionPane.showMessageDialog(null,randomLine);

Upvotes: 5

vidit
vidit

Reputation: 6451

You only read the first line, and that's why you only get the first line. Try this..

String line = reader.readLine();
for (int i = 0; i < randomInt + 1; i++) {
  line = reader.readLine();
}

What you are doing is reading a line from file, using that line to create a new Scanner with every iteration of loop and then read it back into line

Upvotes: 2

Related Questions