简体   繁体   中英

Why does my method sometimes print multiple lines?

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

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

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;

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.

在此处输入图片说明

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