rotibakar
rotibakar

Reputation: 23

Using scanner as parameter

Is this program correct to use the scanner as a parameter? If not, what needs to be fixed

And can you explain what happens in the process of the code? I will be very grateful for your help.

public static void revNumbers(Scanner in) {
    if(!in.hasNextInt())
        return;
    int num = in.nextInt();
    revNumbers(in);
    System.out.println(num);
}

public static void main(String[] args) {
    revNumbers(new Scanner(System.in));
}

Upvotes: 0

Views: 61

Answers (1)

Utkarsh Sahu
Utkarsh Sahu

Reputation: 419

Well, this code works fine... Scanner can be passed as an object so no issue in that... As far as your question (as per your comment) that why does it print in reverse, read this:

Let's suppose you enter 21,15,18,abc one by one, you get output as 18,15,21 obviously in new lines.

Input : 21. The if() condition in the revNumbers method is false. num = 21. But what next? revNumbers method is called in itself! Now revNumbers method works again...

Input 15. The same process goes on as earlier. Again the revNumbers method is called. This happens for 18 as well. So far we have been going into a method from that method itself. It is like concentric circles. The outermost circle be like the first time the method was called and the innermost circle be like the last time the method was invoked.

Concentric Circles

When you are running in the innermost method, actually all the methods encountered earlier but not returned are working but not in the main focus. The most recently invoked method is in the focus. Now when you return, you first terminate the method you last encountered. It works like a stack, first in last out. This process is called recursion.

Now when you input abc, the if() condition becomes true. return statement is encountered. The control goes back to the method when 18 was input. print statement being encountered, 18 is printed first. Then, the method gets terminated so the control goes back to where this method was called again like coming out of the concentric circles... print statement so 15 printed. Then again method terminated so control going back to where the current running method was called. Thus, now it prints 21...

Note: The values of variables is not lost unless the method is terminated (if it is declared within that method) even if control is not in that method. But this variable is not accessible unless the control is present in that method.

Upvotes: 1

Related Questions