0

该程序创建了一个名为 datafile.txt 的文件,并且应该使用文本 I/O 将随机创建的 100 个整数写入文件中。但是,我的输出是“java.util.Random@30c221”100 次。如何获得 100 个随机数?提前致谢。

import java.io.*;
import java.util.Random;

public class Lab5 {

public static void main(String args[]) {

    //Open file to write to
    try {
        FileOutputStream fout = new FileOutputStream("F:\\IT311\\datafile.txt");


    int index = 0;

    //Convert FileOutputStream into PrintStream 
    PrintStream myOutput = new PrintStream(fout);
    Random numbers = new Random();
        //Declare array
        int array[] = new int[100];
        for (int i = 0; i < array.length; i++)
        {
        //get the int from Random Class
        array[i] = (numbers.nextInt(100) + 1);

        myOutput.print(numbers + " ");
        }
    }
    catch (IOException e) {
        System.out.println("Error opening file: " + e);
        System.exit(1);
    }
}    
}
4

3 回答 3

0

替换此行

myOutput.print(numbers + " ");

用这段代码

myOutput.print(array[i] + " ");

因为新生成的随机数现在出现在array.

于 2013-07-08T03:57:11.467 回答
0
myOutput.print(numbers + " ");

你在Random这里打印类实例。

您需要执行以下操作:

myOutput.print(numbers.nextInt(100)+ " ");

阅读随机类文档

编辑:

不,只是array会再次打印类似的输出(对象字符串),如果要输出存储在数组中的随机值,则需要执行以下操作:

myOutput.print(array[i] + " "); 
于 2013-07-08T02:38:27.960 回答
0
Random numbers = new Random();
for (int i = 0; i < array.length; i++)
{
    myOutput.printf("%d\n",numbers.nextInt(100)+1);
}
于 2013-07-08T02:40:59.020 回答