Tarun Kumar
Tarun Kumar

Reputation: 11

Math.Random Function in Java

I have used the below Java code to generate random numbers using math.random function

public class randomnumber {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int num = generatenumber(35);
        while(num>0 & num < 35) {
            System.out.println(num);
            break;
        }
        //System.out.println("greater");
    }

    public static int generatenumber(int n) {
        double d= Math.random() * 100;

        int x = (int)d;
        //System.out.println(x);
        return x;
    }
} 

However, the output is not being displayed when the number is greater than 35. I want the program to print until num is less than 35. What should I change so that it will do that?

Clarification:

Each time this Math.random() generates a random number. On the the first call, if the number generated is greater than 35 ,then I want this function "generate number " to be called again so that next time if the number is less than 35, that number is printed.

Upvotes: 0

Views: 255

Answers (3)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

You wrote:

int num=generatenumber(35);
while(num>0 & num < 35)
{
    System.out.println(num);
    break;
}

You mean to generate and test many times but in fact you're passing zero or one time in your loop depending on the value of num.

The correct code according to your "specs" is

int num;
while(true)
{
    num = generatenumber(35);
    System.out.println(num);

    if (num>0 && num < 35)  // note the double &&: logic and not arithmetic
    {

    break;
    }
}

General note: while loops with conditions are most of the time more complicated than with a true. You have to think of an initialization AND a termination condition, which is sometimes the same. Too much copy/paste and errors...

shmosel suggestion is even better using do/while:

int num;
do
{
    num = generatenumber(35);
    System.out.println(num);        
}
while (num>0 && num < 35);  // note the double &&: logic and not arithmetic

Upvotes: 1

Nicolas Henneaux
Nicolas Henneaux

Reputation: 12205

You can use the following code.

public static void main(String[] args) {
    int num = ThreadLocalRandom.current().nextInt(100);
    for (; num > 35; num = ThreadLocalRandom.current().nextInt(100)) {
        System.out.println(num + " is ignored");
    }
    System.out.println(num + " is ok");
}

Upvotes: 0

Jandisson
Jandisson

Reputation: 380

There are three mistakes:

  1. You should use && instead of &. This two operators are quite different.
  2. The line "int num=generatenumber(35);" should be inside the while too.
  3. You need to remove the break statement.

Upvotes: 1

Related Questions