简体   繁体   中英

Reusing math.random

I am making an app in Android studio that creates a series of random numbers and then uses them to make an equation, that the user answers.

The problem I have is that after they have awnsered correctly and press a button to generate a new equation, the program uses the same numbers it randomized the first time.

Things I have tried: putting the array outside the method, under class.

Using both Math.random and Random rng = new Random() .

Make sure that the method is started several times, using System.out.println .

I have also tried the code in Eclipse, where it works like it should.

The randomiser in my code:

public void SkapaUppgift() {

    System.out.println(test);
    test=test+1;

    for (int i = 0; i < tal.length; i++) {
        Random rng= new Random();
        tal[i] = (int) (Math.random() * ((200 - 0) + 1) + 0);
        //tal[i] = rng.nextInt(200);
    }
}

edit: to clarify. I have used both Random rng AND math.random, and both have been specified to a range between 0 and 200. The problem is that every single time i call the method, the same random number gets pulled. For example: I start the app and get the number 20, 25, 200 and 3. The next time I call the method, I get 20, 25, 200 and 3. The third time I get 20, 25, 200 and 3. If I close the app and start it again, I get 4 different numbers. I want to get different numbers each time I call the method, not just when I restart the app.

You're creating a new Random instance, but not using it. Try using rng.nextInt() instead of Math.random() .

The reason why this is not working is because Math.random() returns a random double between 0 (inclusive) and 1 (exclusive), but it's being downcast to an int, and, thus, being truncated, leaving you with only 1 possible outcome.

EDIT: In that case, you will need to include more code. Where is this being called from? Where are the results being printed out? I have a feeling that this method is working properly and you're actually just printing the same array each time.

Remember that objects in Java are passed by value, not by reference.

You should get the results you want from rng.nextInt(). You just have to make sure you only make it one time and use the same instance forever after . In other words, make it a Singleton.

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