0

Im new to Java and I'm having a little problem writing a series of random number to an output file. I need to used RandomAccessFile and writeDouble. Here is that pice of my code any idea why this is happening. Thanks

private static void numGenerator(int values){
    Random generator = new Random();
    for (int i = 0; i < values; i++) {
        double number = generator.nextInt(200);
        System.out.println(number);
        String outFile = "output.txt";
        RandomAccessFile outputStream = null;
        try{
            outputStream = new RandomAccessFile(outFile,"rw");
        }
        catch(FileNotFoundException e){
            System.out.println("Error opening the file " + outFile);
            System.exit(0);
        }
        number = outputStream.writeDouble(number); //ERROR
    }
}

EDIT: Error: Type mismatch: cannot convert from void to double

0

2 Answers 2

3

The error makes sense. You're writing into a RAF, and per its API the writeDouble method returns void. Why are you trying to set a number equal to this? This statement makes no sense:

number = outputStream.writeDouble(number);

Instead just do:

outputStream.writeDouble(number);

Also, why create a new RAF with each iteration of the for loop? Don't you instead want to create one file before the for loop and add data to it inside of the loop?

Also, why use a RAF to begin with? Why not simply use a text file?

Sign up to request clarification or add additional context in comments.

4 Comments

Im trying to get the random number im generating and copy them to the file
You're doing that with writeDouble.
But it's not a text file. It's a file of bytes. I'm guessing that you may be mistaken by using a random access file here.
@user1354275: to allow us to better help you, please tell us more about what your goal is and why you've decided on using a random access file (RAF) to store your data.
2

Three things that jump out at me:

  1. You're using nextInt() instead of nextDouble().
  2. Your IO operation isn't inside of the try...catch block. Any call to any method that throws any exception must be inside of a try...catch block. (Alternatively, if the method you're using has the signature throws Exception, then the try...catch block is unnecessary. But somewhere, you'll need to handle the exception if/when it's thrown.)
  3. The return value of any of the write methods in RandomAccessFile are void. You won't be able to capture that in a variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.