samedi 30 mars 2019

Why does this piece of code write/print all 0.0 instead of different random numbers?

I'm trying to generate random numbers and write them to a file, then print them. Instead all zeros such as this 0.0 are printed by line in the console and in the file its written in ASCII code.

I have already tied using different java input classes and using the random number generator.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.Random;


    public static void main(String[] args) throws IOException {
        makefile(10, "inputHW02.txt");

        double[] sizearray0 = new double[10];
        int i = 0;
        Scanner inFile;

        inFile = new Scanner(new File("inputHW02.txt"));

        while (inFile.hasNextDouble()) {
            sizearray0[i] = inFile.nextDouble();
            i++;
        }

        for (int r = 0; r < sizearray0.length; r++)
            System.out.println(sizearray0[r]);

        inFile.close();
    }

    public static void makefile(double n, String filename) throws IOException {

        FileOutputStream writer = new FileOutputStream(filename);
        DataOutputStream dos = new DataOutputStream(writer);
        Random rand = new Random();

        for (int i = 0; i < n; i++) {
            dos.writeInt((int) 60);
            ;

        }
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }

I expect the file and output console should have random numbers separated on a new line such as 10.0 23.0 1.0 and so forth.




Aucun commentaire:

Enregistrer un commentaire