siggi376
siggi376

Reputation: 3

Using math.random to generate a certain amount of random numbers in java

I need help making a program in java that lets you write a number in textField and then generate that amount of random numbers from 0-9 using i = (int) (Math.random() * 10.0). For example if I would write 5 in the textField the program would generate 5 random numbers from 0-9.

Thanks

Upvotes: 0

Views: 1115

Answers (3)

Peter Walser
Peter Walser

Reputation: 15706

Using the new Java 8 streams API:

int n = Integer.parseInt(myTextField.getText());
int[] random = ThreadLocalRandom.current().ints(0, 10).limit(n).toArray();
  • uses the current thread local random (recommended over creating a new Random instance)
  • creates a random stream of integers in the range [0..10) -> 0..9
  • Stream terminates after n numbers have been generated
  • the stream result is collected and returned as an array

Upvotes: 1

theVoid
theVoid

Reputation: 743

Ok since you want to use the Math.random() method try the following:

    int times = 5;//how many numbers to output

    for(int i = 0; i < times; i++)
    {
        System.out.println((int)(Math.random()*10));
        //you must cast the output of Math.random() to int since it returns double values
    }

I multiplied by 10 because Math.random() returns a value greater than or equal to 0.0 and less than 1.0.

Upvotes: 0

Ashish Sharma
Ashish Sharma

Reputation: 220

int x = value entered in textfield;
int generatedRandomNumber = 0;
java.util.Random rand = new java.util.Random();
for(int i=0 ; i<x ; i++) {
    generatedRandomNumber=rand.nextInt(10);//here you have your random number, do whatever you want....
}

Upvotes: 0

Related Questions