简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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