I am required to write a recursive method. I have written the code to perform the task without recursion. I am getting the error Exception in thread "main" java.lang.StackOverflowError at Exercise13r.recursion(Exercise13r.java:29). Code is... to enter a number then if result is even, divide by 2, if result is odd, multiply by 3 and subtract 1. Obviously I am looping but not sure why. Any assistance would be appreciated.
import java.util.Scanner;
public class Exercise13r
{
public static void main(String[] args)
{
// Initialize variables
long number = 0;
Scanner in = new Scanner(System.in);
System.out.println ("Enter a starting number: ");
number = in.nextInt ();
System.out.println ("Your starting number is: " + number);
if (number != 1)
{
recursion(number);
}
}
public static void recursion(long n)
{
if (n % 2 == 0)
{
recursion(n/2);
}
else
{
recursion(n*3-1);
}
System.out.println ("number: " + n);
return;
}
}
recursion. As it stands, both branches of theifcall the function again, and it loops forever.recursionmethod?