Why Java call stack behaves differently according to order of the inputs

Viewed 100

I have been doing my homework about recursion and I realized something very strange.

import java.util.Scanner;
public class Recursive{

    public static void main ( String [] args){
        Scanner scan = new Scanner(System.in);
        while(true){
            System.out.println("Please Enter the Number");
            int n = scan.nextInt();
            int upper = (int)Math.pow(10, n);
            int lower = (int)Math.pow(10, n - 1);
            printNumbers(upper, lower);
        }
    }

    public static void printNumbers(int upperBound , int lowerBound){
        if(upperBound < lowerBound){
            System.out.println("Start Point");
        } else if (isOrdered(upperBound)){              // Line 18
            int holder = upperBound;
            printNumbers(upperBound - 2, lowerBound);
            System.out.print(holder + " ");
        } else{
            printNumbers(upperBound - 2, lowerBound);   // Line 23
        }
    }

    public static boolean isOrdered(int number){    
        if(number < 10) return true;
        return (number % 10 > (number / 10) % 10) && isOrdered(number / 10);
    }
}

At the above code, the program checks whether or not digits in the number are increasing order left to right. I ask for user to enter input n to find out how many digits each number will have. Program works perfectly find for the n values 1 , 2 , 3 , 4. But the program acts strange when we enter in different order. For example, I can enter 4 as many as I want but when I enter 3 and 4, program crashes with infinite recursion in the printNumbers method. I do not understand that since the program works for 3 and for individually but we enter 3, get the result we enter 4 and it crashes Why it is crashing?

PS: I made the while(true)at the main method just for checking. At the below it is the stack trace.

Exception in thread "main" java.lang.StackOverflowError
    at Recursive.printNumbers(Recursive.java:18)
    at Recursive.printNumbers(Recursive.java:23)
    at Recursive.printNumbers(Recursive.java:23)
    at Recursive.printNumbers(Recursive.java:23)
    ...
0 Answers
Related