簡體   English   中英

隨機不打印出正確的最大值和最小值

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

我試圖讓用戶將他們想要的最大值和最小值輸入到一個隨機數的新文件中。 然而,當我運行我的程序時,生成的隨機數總是小於我想要的最小值。 例如,如果 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();
        }   
    }
}

代替

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

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

問題是您沒有正確生成隨機數。 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