Home > Software engineering >  Random method always returning minimum value in for-loop?
Random method always returning minimum value in for-loop?

Time:12-11

I'm utilizing a random method that I created, rather than the java.util.Random class. The class is called "Randomizer", here is the code within it:

public class Randomizer{
  public static int nextInt(){
    return (int)Math.random() * 10   1;
  }

  public static int nextInt(int min, int max){
    return (int)Math.random() * (max - min   1)   min;
  }
}

This code should work just fine, but when I call it in a for loop (as seen below), it always returns the minimum value.

public class Main
{
    public static void main(String[] args)
    {
        System.out.println("Results of Randomizer.nextInt()");
        for (int i = 0; i < 10; i  )
        {
          System.out.println(Randomizer.nextInt());
        }
        int min = 5;
        int max = 10;
        System.out.println("\nResults of Randomizer.nextInt(5, 10)");
        for (int i = 0; i < 10; i  )
        {
          System.out.println(Randomizer.nextInt(min, max));
        }
    }
}

This code returns the following:

Results of Randomizer.nextInt()
1
1
1
1
1
1
1
1
1
1

Results of Randomizer.nextInt(5, 10)
5
5
5
5
5
5
5
5
5
5

I think this error has to do with the fact that the methods within Randomizer are static, but I can't imagine how I could fix this. Any help would be greatly appreciated!

CodePudding user response:

Math.random() returns a floating point number (double) in the range [0, 1). When you cast that double to an integer, it truncates to 0 every time.

To solve your problem, you need to do the casts after all of the math you are trying to do. So, it should look like this:

public class Randomizer{
  public static int nextInt(){
    return (int)(Math.random() * 10   1);
  }
  public static int nextInt(int min, int max){
    return (int)(Math.random() * (max - min   1)   min);
  }
}

Note the extra parentheses around the expression to be cast to an integer.

  • Related