Home > Enterprise >  Java: print multiple random lines from text file
Java: print multiple random lines from text file

Time:11-24

I am currently learning Java and received the following task, that I cannot seem to solve:

"Create a Java program that prints one random poem of 5 lines in the console. The poems must be read from a text file."

I have copied 10 different poems inside a text file, all written underneath each other. I managed to make the program print out the very first poem (first 5 lines) in the console, but first of all, I am not sure if it's the correct way to do such, and I don't know how to make the program print out one random poem (5 lines that belong together) each time I run it.

Here is the farthest I could get:

public static void main(String[] args) throws IOException {
    File file = new File("src/main/java/org/example/text.txt");

    Scanner scanner = null;
    try {
        scanner = new Scanner(file);

        int i = 0;
        while (scanner.hasNext()) {
            String line = scanner.nextLine();
            if (i < 5) {

                i  ;
                System.out.println(line);
            }
        }
    } catch (Exception e) {

    }
}

CodePudding user response:

You can try

private static final int POEM_LINES_LENGTH = 5;

public static void main(String[] args) throws IOException
{
    // The file
    File file = new File("src/main/java/org/example/text.txt");
    
    // Get all the lines into a single list
    List<String> lines = Files.readAllLines(Paths.get(file.getAbsolutePath()));
    
    // Get a random poem and point at the end.
    int poemFinish = new Random().nextInt(lines.size() / POEM_LINES_LENGTH) * POEM_LINES_LENGTH;
    
    // Point to the be start
    int start = poemFinish - POEM_LINES_LENGTH;
    
    // Create a sublist with the start and finish indexes.
    for (String line : lines.subList(start, poemFinish))
        System.out.println(line);
}

CodePudding user response:

This will not read the entire file into the memory, hence large files can also be read.

  final int totalPoems = 17;
  int skip = new Random().nextInt(totalPoems) * 5;

  Path path = Paths.get("file.txt");
  BufferedReader reader = Files.newBufferedReader(path);
    
  while(skip-->0){
     reader.readLine();
  }
  
  for(int i=0; i<5; i  ){
      System.out.println(reader.readLine());
  }

The downside is you have to know how many poems are in the file beforehand. If you don't want to do this you can quickly count the total number of lines/poems only one time.

  • Related