【问题标题】:Random not printing out right max and min values随机不打印正确的最大值和最小值
【发布时间】:2020-09-02 20:20:03
【问题描述】:

我试图让用户将他们想要的最大值和最小值输入到一个随机数的新文件中。但是,当我运行我的程序时,生成的随机数总是小于我想要的最小值。例如,如果 max = 10 和 min = 5,我只能得到 0 到 5 之间的数字。我想知道如何才能得到 5 到 10 之间的数字。我假设要找到 max 和 min该函数应该是 (max - min) + 1 但它对我不起作用。

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

public class chooseRandNum{
    public static void main(String[] args){
        Random rand = new Random();
        Scanner key = new Scanner(System.in);
        System.out.println("How many random numbers do you want? ");
        int totalRand = key.nextInt();
        System.out.println("What is the smallest random number? ");
        int smallRand = key.nextInt();
        System.out.println("What is the largest random number? ");
        int largeRand = key.nextInt();
        System.out.println("What filename do you want to use? ");
        String fname = key.nextLine();

        File outputFile = new File(fname);
        PrintStream outputStream = null;

        try{
            outputStream = new PrintStream(outputFile);
        }

        catch (Exception e){
            System.out.println("File not found " + e);
            System.exit(1);
        }


        for(int i = 0; i <= 5; i++){
            for(int j = 0; j <= totalRand; j++){
                int n = rand.nextInt((largeRand - smallRand) + 1);
                outputStream.print(n + ",");
            }
            outputStream.println();
        }   
    }
}

【问题讨论】:

    标签: java for-loop random max min


    【解决方案1】:

    替换

    rand.nextInt((largeRand - smallRand) + 1)
    

    rand.nextInt(largeRand - smallRand + 1) + smallRand
    

    【讨论】:

      【解决方案2】:

      问题是您没有正确生成随机数。 rand.nextInt(max-min+1)+min 应该在 [min, max] 中给出一个随机整数,因为 rand.nextInt(int) 调用提供一个整数 [0, int) Java Documentarion of java.util.Random.nextInt

      【讨论】:

        猜你喜欢
        • 2018-04-09
        • 1970-01-01
        • 2020-09-06
        • 2015-02-20
        • 1970-01-01
        • 2018-07-08
        • 1970-01-01
        • 2019-05-26
        • 2021-07-09
        相关资源
        最近更新 更多