【发布时间】: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