Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Random method always returning minimum value in for-loop?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading