3

I am having trouble with the RandInt() method as it will not return a random integer. The result must be an int ranged 0-9 and must use the math.random class. This is my code below:

public class RandNumGenerator {
    public static int RandInt() {
        int n = (int) Math.random() * 10;
        return n;
    }
    public static void main(String[] args) {
        RandInt();
    }
}
KeyNone
  • 8,745
  • 4
  • 34
  • 51
rico99
  • 77
  • 1
  • 3
  • 10

4 Answers4

5

You should cast the double to int after multiplying by 10 :

int n = (int) (Math.random() * 10);

Otherwise you'll always get 0 (since Math.random()<1.0 and therefore (int)Math.random() is always 0).

Eran
  • 387,369
  • 54
  • 702
  • 768
3

Casting has higher priority than * so code

(int) Math.random() * 10;

is same as

((int) Math.random()) * 10;

and since Math.random() returns values in range [0; 1) (1 - excluded) casting to int

(int) Math.random()

will produce 0 which multiplied by 10 will also return 0.

You may want to use

(int) (Math.random() * 10)

or easier to read and maintain Random#nextInt(max) to generate range [0; max) (max-exclusive)

Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

You need to put brackets around the multiplication

int n = (int) (Math.random() * 10);

what's happening is

int n = ((int) Math.random()) * 10;

as Math.random() is always greater or equal to 0 and less than 1, converting it to an integer will always equal zero. Multiplying it by 10 will do nothing.

Jezzamon
  • 1,453
  • 1
  • 15
  • 27
-1

You shouldn't really be using Math.random() to generate random integers, as it will generate random floats (i.e, decimal numbers)

You should do something similar to this

Random myRandom = new Random();
int randomInt = myRandom.nextInt(10);
Storm-
  • 147
  • 8
  • 1
    OP: `must use the math.random class.` – Marko Topolnik Jul 26 '15 at 12:41
  • @MarkoTopolnik Asking a method to return an integer when it's set to return a float is quite literally impossible. Unless you want to cast it, which is pointless when the Math.random uses the Random class anyway. – Storm- Jul 26 '15 at 12:54
  • 1
    *using* a method in a calculation is different from *asking* it to return the end result. You appear to be alone in your interpretation of OP's goal. – Marko Topolnik Jul 26 '15 at 12:57
  • @MarkoTopolnik In what scenario would casting the return value of a method to what you want, be better than using a method that does the exact same thing without casting? The only reason I see for doing this, is in an educational environment, in which case the OP shouldn't be learning to do things inefficiently. – Storm- Jul 26 '15 at 13:00
  • 1
    So ask OP to give you a contact to his educational institution, then complain about their curriculum. Meanwhile, OP will be expected to do what the assignment asks for. – Marko Topolnik Jul 26 '15 at 13:02
  • @MarkoTopolnik Touche. – Storm- Jul 26 '15 at 13:05