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.
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();
}