如何在java中打印5到25之间的20个随机数?

时间:2015-03-09 12:49:16

标签: java random

我正在使用Java。我想让用户输入5到25之间的数字。让我们说用户输入6.程序然后需要打印6个随机数。当用户输入20时,程序必须在5到25之间打印20个随机数。

3 个答案:

答案 0 :(得分:0)

嗯,你至少应该告诉我们你曾尝试做过什么:),下次还要记住。

这是一段代码:

import java.util.Random;
import java.util.Scanner;

public class JavaApplication2 {
    public static void main(String[] args) {
        Random random = new Random();        

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number");
        int inputNumber = in.nextInt();
        for (int i = 0; i < inputNumber; i++) {
            int generatedNumber = random.nextInt(inputNumber)+5;
            //int generatedNumber = random.nextInt(20)+5; //Use this line instead of above one to have always range 5-25, no matter the input size.

            System.out.println("Generating number " + i + ": " + generatedNumber);
        }
    }   
}

示例输出:

Enter the number
20
Generating number 0: 20
Generating number 1: 15
Generating number 2: 10
Generating number 3: 10
Generating number 4: 6
Generating number 5: 14
Generating number 6: 15
Generating number 7: 16
Generating number 8: 14
Generating number 9: 10
Generating number 10: 15
Generating number 11: 20
Generating number 12: 13
Generating number 13: 21
Generating number 14: 22
Generating number 15: 20
Generating number 16: 8
Generating number 17: 17
Generating number 18: 22
Generating number 19: 5

PS:我不确定“范围”究竟应该如何运作,你没有解释......

答案 1 :(得分:0)

使用用户指定的计数生成两个范围之间的随机数

import java.util.Random;
public final class RanGen {  
  public static final void main(String... aArgs){       

    int max=10;// min range
    int min=5;//max range
    int userInput = 6;// how many numbers should generate
    int diff=max-min;

    //note a single Random object is reused here
    Random randomGenerator = new Random();
    for (int idx = 1; idx <= userInput; ++idx){     
            Random rn = new Random();
            int i = rn.nextInt(diff+1);
            i+=min;
            System.out.print("The Random Number is " + i);      
    }
  }
}

答案 2 :(得分:0)

你可以试试这个:

public class NumerosAleatorios {


private static int[] arrayDeNumeros;

public static int[] list(int numero){
      arrayDeNumeros = new int[numero];
for(int i=0;i<arrayDeNumeros.length;i++)
{
    arrayDeNumeros[i] = randomFill();
}
return arrayDeNumeros;
}



public static int randomFill(){

Random rand = new Random();
int randomNum =rand.nextInt(25)+5;
return randomNum;
}

public static void main(String args[]) {

}

}