-4

I'm fairly new to Java so bear with me. I'm making a recursive method in Java that allows me to input a number X and have the system print each value in decrements of 2 until it reaches 1. (I'll have to add a rule that the scanner can only take odd numbers too). I set up the scanner but it doesn't seem to be picking up the value I assign to n.

public class Recursividad {

        public static int Func(int n)
        {
            if (n != 1)
                return 0;
            else 
                return Func(n-2);
        }

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int x = Func(n);
    System.out.println(x);
}

}

The output is always 0.

Dotol
  • 376
  • 1
  • 4
  • 19

2 Answers2

2

Dotol, its taking input from scanner and assigning it to n also. But the logic you are using in recursive function Func(int n) is always returning 0 because you are using if(n!=1) means whenever you enter anything but n it always return 0.

P.S. you need to check your code. Also you can do little debugging to know where you are wrong.

somprabhsharma
  • 323
  • 2
  • 12
1

When you tell your program to return 0 if n!=1 , then it'll return 0 if n != 1. Therefore, it'll always print out 0 unless you pass 1 as argument, which would end up in an infinite loop.

Also, if you want to print out something every time, your command to do so should be inside your function, not outside. If your System.out.println is put outside of your recursive function, it would be run only after the whole recursion is finished, and consequently, it would print out only the last number.

Your code should look something like this

public class Recursividad {

    public static int Func(int n)
    {
        System.out.println(n);
        if (n == 1)
            return n;
        else 
            return Func(n-2);
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int x = Func(n);
    }
}

PS: Also consider checking if the number gets to 0 or negative

rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • Thanks that worked perfectly I didn't know how the return worked. I applied the changes that you suggested and changed the {if (n != 1)} to {if (n <= -1) as the homework had to show all numbers in between down to 1. And I still can't figure out how to stop the input value of the variable 'n' from displaying twice in the output display. Thanks a lot! – Dotol Feb 22 '16 at 04:59