简体   繁体   中英

Random line from a file.txt

Any tips why my random doesn't work? All i get in input are stacked lines from first to 11. I think it will be a small mistake but i can't figure it out :/

package pl.mtgpackgenerator;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;

public class Test {
public static void main(String[] args) throws IOException {

    Random random = new Random();
    int randomInt = random.nextInt(59);
    FileReader fr = new FileReader("Common.txt");
    BufferedReader reader2 = new BufferedReader(fr);
    String line = reader2.readLine();

    for (int i = 0; i <= 10; i++) {
          line = reader2.readLine();
          System.out.println(line);
        }
    reader2.close();
    }
}

We need to use randomInt to check the line number and only print that line, if exists (example below). In the above code, randomInt is not used anywhere.

int index = 0;
while( (line = br.readLine() ) != null) {
    if(index++ == randomInt){
        System.out.println(line);
        break;
    }
}

Well, it looks for me as you are explicitly reading first 10 lines from the file, and you don't use your random.

You may, for example, read all lines to an ArrayList of Strings , one by one, and then use your randomInt to print a line at the randomInt number. Just use it like arraylist.get(randomInt) ; if you named your list arraylist .

@gliacomo said if you refers the code do this:

public static void main(String[] args) throws IOException {

    Random random = new Random();
    int randomInt = random.nextInt(59);
    FileReader fr = new FileReader("Common.txt");
    BufferedReader reader2 = new BufferedReader(fr);
    for (int i = randomInt; i <= randomInt + 10; i++) {
        String line = reader2.readLine();
        System.out.println(line);
    }
    reader2.close();
}

In Java 1.8 you can do like this

import java.nio.file.Files;
...
Random random = new Random();
int randomInt = random.nextInt(59);
List<String> lines = Files.readAllLines(new File("Common.txt"))
String resultString = lines.get(randomInt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM