user1171076
user1171076

Reputation:

Recursive random number generator

I need help on my code. My code is functioning but I was instructed to make it recursive when generating a random number. Can someone help me what to add on my code?

Here's the code:

    import java.util.*;


    public class random{

        public static void main (String[]args){

            int number;
            Random rnd = new Random();

            number = rnd.nextInt(100);

                  while(number > 0){
                      number--;
                      System.out.println(number);

                  }
         }
     }

Upvotes: -1

Views: 3942

Answers (3)

Savino Sguera
Savino Sguera

Reputation: 3572

Recursion is an important concept, and can be tricky to deeply understand.

I'd suggest you close this browser tab, take an algorithms book, pencil and paper, and start "unrolling" recursive calls from examples you find online, until you understand where it starts and (especially) where it stops. Also look at recurrence relations, if you feel formal.

Take factorial or recursive Fibonacci, and think about it, write code, get your hands dirty. You will get a few infinite loops, but eventually will get it.

My two cents.

PS: review your code style too, respect the language's convention. For java: http://www.oracle.com/technetwork/java/codeconv-138413.html

Upvotes: 4

Adel Boutros
Adel Boutros

Reputation: 10295

import java.util.*;

public class random{

    public static void main (String[]args){
        int number;
        Random rnd = new Random();
        number = rnd.nextInt(100);
        nextRandom(number);
    }

    void nextRandom(int number) {
        if (number <= 0) {
            return;
        } else {
            --number;
            System.out.println(number);
            nextRandom(number);
        }
    }
}

Upvotes: 0

user952887
user952887

Reputation: 425

does this help?

public class random {

    public static void main(String[] args) {

        Random rnd = new Random();

        int number = rnd.nextInt(100);
        print(number);

    }

    public static void print(int num) {
        if (num >= 0) {
            System.out.println(num);
            print(--num);
        }
    }
}

i don't really know what type of recursion do you need...

Upvotes: 2

Related Questions