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

Random not printing out right max and min values

我试图让用户将他们想要的最大值和最小值输入到一个新文件中以获得一个随机数。然而,当我 运行 我的程序生成的随机数总是小于我想要的最小值。例如,如果 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();
        }   
    }
}

替换

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

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

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