Hi all.
This program is meant to do the following:
1: create a new txt file
2: write 100 random integers to it
3: read it back into an array
4: sort the array
5: print contents of array
I have everything working apart from part 2. I can't get it to create 100 numbers. Sometimes it does 50, other times 62, 25, 99 etc.
Not sure on how to fix this. Any help much appreciated.
My code below.
import java.io.*; import java.util.*; public class Q3 { public static void main(String[] args) //Throw any exceptions throws Exception { // Create file called Q3.txt FileWriter newFileWriter = new FileWriter("Q3.txt"); BufferedWriter newFileOut = new BufferedWriter(newFileWriter); //Random Number Generator Random numberGenerator = new Random(); //Write 100 random numbers to Q3.txt for (int i = 0; i < 100; i++) { //while number of numbers is less than 100, increment the counter //and enter a random number to the file followed by a space int randomNumber = numberGenerator.nextInt(100); newFileOut.write(randomNumber + " "); } //Close the file writer newFileOut.close(); //crate file scanner to read file Scanner input = new Scanner(new File("Q3.txt")); //create array with contents of the file int[] array = new int[input.nextInt()]; //every next number is sent to next position on the array for (int i = 0; i < array.length; i++) array[i] = input.nextInt(); //sort the array in ascending order Arrays.sort(array); //parse the array contents to a string and print the string System.out.println(Arrays.toString(array)); //close the file reader input.close(); } }