简体   繁体   English

随机不打印出正确的最大值和最小值

[英]Random not printing out right max and min values

I am trying to allow a user to input what they want for a max and minimum into a new file for a random number.我试图让用户将他们想要的最大值和最小值输入到一个随机数的新文件中。 However when I run my program the random number generated is always less than the minimum I wanted.然而,当我运行我的程序时,生成的随机数总是小于我想要的最小值。 For example, if max = 10 and min = 5 I am only getting numbers between 0 and 5. I was wondering how I can make it so that I get numbers between 5 and 10. I was under the assumption that to find max and min the function should be (max - min) + 1 but it hasn't worked for me.例如,如果 max = 10 和 min = 5,我只会得到 0 到 5 之间的数字。我想知道如何才能做到这一点,以便得到 5 到 10 之间的数字。我假设要找到 max 和 min function 应该是 (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();
        }   
    }
}

Replace代替

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

with

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

The issue is that you are not generating the random number correctly.问题是您没有正确生成随机数。 rand.nextInt(max-min+1)+min should give a random integer in [min, max] because the rand.nextInt(int) call supplies an integer, [0, int) Java Documentarion of java.util.Random.nextInt rand.nextInt(max-min+1)+min应该在 [min, max] 中给出一个随机的 integer,因为rand.nextInt(int)调用提供了一个 integer, [0, int) Java java.util.Random 的文档。下一个整数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM