【问题标题】:Not getting random numbers in output在输出中没有得到随机数
【发布时间】:2013-07-08 02:37:00
【问题描述】:

该程序创建一个名为 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);
    }
}    
}

【问题讨论】:

    标签: java io


    【解决方案1】:
    myOutput.print(numbers + " ");
    

    您在此处打印Random 类实例。

    您需要执行以下操作:

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

    阅读Random class documentation

    编辑:

    不,只是array会再次打印类似的输出(对象字符串),如果你想输出存储在数组中的随机值,你需要这样做:

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

    【讨论】:

    • 所以应该是 myOutput.print(array + " "); ?
    • 或 array[i] 会更好:)
    • @nachokk - print(array ... 不会做你所期望的!!!请参阅有关如何在 Java 中格式化数组的许多问题。
    • 对不起,伙计们。在我发表评论之前,我没有看到 Nambari 的其余答案。 myOutput.print(array[i] + "");工作。非常感谢。
    • @nachokk - 试试看,你会看到的。
    【解决方案2】:
    Random numbers = new Random();
    for (int i = 0; i < array.length; i++)
    {
        myOutput.printf("%d\n",numbers.nextInt(100)+1);
    }
    

    【讨论】:

      【解决方案3】:

      替换这一行

      myOutput.print(numbers + " ");
      

      用这段代码

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-11
        相关资源
        最近更新 更多