Error in recursive function

I am trying to get a pin number of just 4 digits. But numbers that are less than 1000 are also printed. What happens in this code?

import java.util.Random;

public class Util {

    public static int getRandomPINNumber(){
        Random randomGenerator = new Random();
        int randomNo = randomGenerator.nextInt(10000);
        if(randomNo < 1000)
        getRandomPINNumber(); //repeat if it is less than 1000,some bug here
        return randomNo;
    }

    public static void main(String[] args){
        for(int i = 0;i<100; i++)
            System.out.println(getRandomPINNumber());
    }

}

Exit

6413
1692
5734
105  <--- why 105 is getting printed, it should reevaluate the pin right? 
4857
6348
1355
+4
source share
5 answers

The problem is that you are not returning the result of a recursive call. Change your code to:

public static int getRandomPINNumber(){
    Random randomGenerator = new Random();
    int randomNo = randomGenerator.nextInt(10000);
    if(randomNo < 1000)
        return getRandomPINNumber(); //repeat if it is less than 1000
    return randomNo;
}

When you call the function for the first time and a number less than 1000 is generated, you call recursively getRandomPINNumber, but ignore the return value.

In addition, you should not call new Random()several times. Call it once and save the result.

+8
source

Three things in order to increase pedantry

  • : return getRandomPINNumber(); .

  • Random randomGenerator = new Random(); , . randomGenerator .

  • , . ( - ). int randomNo = randomGenerator.nextInt(9000) + 1000; .

+3

, :

    return randomGenerator.nextInt(9000) + 1000;

.

+2

, , if randomNo.

int randomNo = randomGenerator.nextInt(10000);
if (randomNo < 1000) {
    randomNo = getRandomPINNumber(); //repeat if it is less than 1000,some bug here
}
return randomNo;

You can also avoid 1000 values ​​with

int randomNo = randomGenerator.nextInt(9000) + 1000;

This will return numbers from 1000 to 9999 and become a much cleaner solution than recursion.

+2
source

I made the code this way

public class Util {

    static Random randomGenerator = new Random();

    public static int getRandomPINNumber(){
        int randomNo = randomGenerator.nextInt(9000) + 1000;
        return randomNo;
    }


    public static void main(String[] args){
        for(int i = 0;i<100; i++)
            System.out.println(getRandomPINNumber());
    }

}

Posting full error code following information / tips from other answers

0
source

Source: https://habr.com/ru/post/1608775/


All Articles