-4

This is what I have so far. I am having issues with getting the File Writer to work.

import java.util.Random;

public class Sort {

public static void main(String[] args) {
    Random rand = new Random();

    int q = 10000;
        for (int i = 0; i < q; i++) {
            int foo = rand.nextInt();
            System.out.println(foo);
        }
    }
}

I will be using the file to sort later.

rkyr
  • 3,131
  • 2
  • 23
  • 38
Courtney
  • 19
  • 2
  • 5
    "I am having issues with getting the File Writer to work" I don't see any FileWriter in your code. This is first problem you should fix. We can't tell you what you are doing wrong without seeing how are you using this class. – Pshemo Dec 06 '15 at 01:03
  • 1
    You have the logic of your program down. You know you need a FileWriter; You'll have to do some reading up on how to use that class. In a nutshell, you're going to have to create a FileWriter object with whichever constructor you want. Once you have a FileWriter object, just start writing to it instead of printing to System.out. https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html – Nathan Dec 06 '15 at 01:28

1 Answers1

0

How can I write a list of random generated numbers to a file?

For example like this

public static void main(String[] args) {
    try (BufferedWriter writer = Files
            .newBufferedWriter(Paths.get("file.txt"))) {

        for (PrimitiveIterator.OfInt ints = ThreadLocalRandom.current()
                .ints().limit(10_000).iterator(); ints.hasNext();) {
            writer.write(String.valueOf(ints.nextInt()));
            writer.newLine();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

I hope you see how it works. https://docs.oracle.com/javase/tutorial/essential/io/file.html has more information.

zapl
  • 63,179
  • 10
  • 123
  • 154
  • Ok, I now need to read in those numbers and sort them using varying sorting algorithms. The algorithms I am using are from my text book, however I am a little confused how to put in the FileReader in the code. The code consists of sorting an array and the file as I know is not an array. I know there are multiple ways to do this I just don't know if I should create a new class for the file reader or just put it into each of the sorting algorithms. – Courtney Dec 10 '15 at 03:06