简体   繁体   中英

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.

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

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.

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM