How to capture a random line from a text file and print the line

Very new to Java (only a few days in the learning process). I am looking for a random program of quotes. I have quotes on separate lines in the quotes.txt file. What I need is to grab a random string and print it.

I believe that the steps first determine the number of lines in the file, and then generate a random number between 0 and the number of lines. Then go to this line in the file and print it.

I just have no idea how to even get started (again, forgive me, very new to Java). Any help is greatly appreciated.

0
java
source share
3 answers

Here is a brief idea. Note. I have not tested this code. Just put it very fast ... And that should be enough for small files only. If you need to process large amounts of data, I would suggest just reading the file in the line of interest (based on random) and processing only this line. Moreover, other libraries may help in solving this problem (for example, Apache commons: FileUtils.readLines (file) .get (indexNumber))

FileInputStream fs= new FileInputStream("quotes.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fs)); ArrayList<String> array = new ArrayList<>(); String line; while((line = br.readLine()) != null) array.add(line); // variable so that it is not re-seeded every call. Random rand = new Random(); // nextInt is exclusive. Should be good with output for array. int randomIndex = rand.nextInt(array.size()); // Print your random quote... System.out.println(array.get(randomIndex)); 
+1
source share

What I would do is create an ArrayList and add the lines there. Get a random number between 0 and (ArrayList - 1 in size) and get the value of the information stored in this index. I will leave the code for you to try to figure out, however I will help when you post your code that you already wrote.

+2
source share
  • Read the file in List or array . A Scanner or BufferedReader can accomplish this.
  • Use the Random class to generate a random number between 0 (inclusive) and the size of the array / list (exclusive).
  • Use the result from (2) to access the index of this element in the / List array from (1).
0
source share

All Articles