0

I am new to Java and stackoverflow. I have a text file that I wish for my Java program to read and then pick a random line and display it. 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");

    }

}

1 Answers1

0

I suggest you use a buffered reader. With in.readLine() you can get your next line from the file.

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.

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()) ));
nitowa
  • 1,079
  • 2
  • 9
  • 21
  • You might be right on that one. Comparing with null will certainly work, so I'll use that for safety. – nitowa Nov 23 '14 at 22:32
  • Random thought: Using an ArrayList is not the most effective implementation in this case. A LinkedList is a lot faster since you add multiple times but get only once. --efficiency comparison ArrayList : Adding O(n), Getting O(1) LinkedList: Adding O(1), Getting O(n) – nitowa Nov 23 '14 at 22:43
  • I need each line in the text file to have an equal chance of being read as other lines. Which of the two strategies would work better for this to work? – shottyrockets Nov 24 '14 at 17:24