2

So I Have this method

public int sumMathRandomAndSystemTime(){

    n = 1 + ((int) (Math.random() * 10)+ 
            (int) (System.currentTimeMillis() % 10));

    if(n > 10){
        sumMathRandomAndSystemTime();
    }
    System.out.println(n);
    return n;

}  

All I want is to print one random number (n) between 1 and 10 once. But for some reason, when I call the method it does print a random number, but some times only once, other times it prints the number like 10 times, 5 times, etc. Why is this happening?

Here's an example of my output

10
10
10
10
10

3 Answers3

3

IF the original random number is larger then 10, your code will print multiple lines: one for each recursive call.

You can change your code as following to solve this problem:

public int sumMathRandomAndSystemTime(){

    int n = getRandomNumber();
    System.out.println(n);
    return n;

}

public int getRandomNumber() {
    int n = 1 + ((int) (Math.random() * 10)+
            (int) (System.currentTimeMillis() % 10));

    if(n > 10){
        n = getRandomNumber();
    }
    return n;
}

And in general a much simpler code would be:

public int sumMathRandomAndSystemTime(){
    Random random = new Random();
    int n = random.nextInt(10);
    System.out.println(n);
    return n;
}
Adiel Loinger
  • 199
  • 11
1

If you only want to print one random number between 1 and 10, try something like this...

        int n;
        do
        {
          n = 1 + ((int) (Math.random() * 10) + (int) (System.currentTimeMillis() % 10));
        } while(n > 10);

        return n;
codemonkey
  • 58
  • 1
  • 8
1

Add return statement after sumMathRandomAndSystemTime(); call.

public static int sumMathRandomAndSystemTime(){
    n = 1 + ((int) (Math.random() * 10)+ 
            (int) (System.currentTimeMillis() % 10));
    if(n > 10){
        sumMathRandomAndSystemTime();
        return n;
    }
    System.out.println(n);
    return n;
}  

May be this picture can clear the flow.

enter image description here

gifpif
  • 4,507
  • 4
  • 31
  • 45