简体   繁体   中英

How to read N number of lines from a file in java randomly

I am fairly new to java, so please bear with me if I have done something wrong. I have written a code in java that reads in N number of lines from a file in java and puts it in array of double and then prints it out;

ArrayList<Double> numbers = new ArrayList<Double>();
Scanner read = new Scanner(new File("numberfile"));
int counter = 0;
while(read.hasNextLine() && counter < 10)
{
    System.out.println(read);
    counter++;
}

The file contains bunch of numbers from 1 to 100;

Currently, my code prints out all the numbers like this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], if I tell it to read the first 10 numbers. What I want to do now is print out these numbers in a random order, for example [2, 1, 6, 8, 9, 3, 7, 10, 3, 5].

And also if possible, I want to write a code that prints out the first 10 numbers randomly N number of times. For example, print out the first 10 numbers 50 times in a random order.

Thanks for your help and please let me know if I am unclear.

您可以将它们放入List ,然后使用Collections.shuffle方法。

Read your numbers into an array , and java.util.Random to access your array and print as you wish (use a nested loop for printing 'x' number of times per access). If you just want to print randomly, you can use Collections.shuffle to shuffle and then simply iterate through the structure and print.

Well, if your file is small enough, using Java 7 it's easy:

final Path thefile = Paths.get("whereyourfileis");

final List<String> lines = Files.readAllLines(thefile, StandardCharsets.UTF_8);

Collections.shuffle(lines);

// lines.sublist(0, 10) --> done

You should store the numbers as you read the file into an array (or list) and then either A) shuffle the array and print it out, or B) randomly select numbers from the array. If you don't care about repeated numbers (for example, [2, 1, 6, 1, 1, 1, 2]) you can just pick 10 items random using Math.Random(). Otherwise, read into a List as follows (you already have an ArrayList called numbers):

while(read.hasNextLine() && counter < 10)
{
    numbers.add(read.nextDouble());
    counter++;
}
for (int n = 0; n < 50; n++) {
    Collections.shuffle(numbers);
    for (int i = 0; i < numbers.size(); i++) {
        System.out.println(numbers.get(i));
    }
    System.out.println();
}

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