I have come across the below code while searching some answers.
public static void recurse(Scanner in, HashMap<String, Integer> oldMap) {
HashMap<String, Integer> map = null;
if (oldMap == null)
map = new HashMap<String, Integer>();
else
map = new HashMap<String, Integer>(oldMap);
while (in.hasNext) {
String s = in.nextLine();
if (s.startsWith("[")) {
recurse(in, map);
continue;
}
if (s.startsWith("]")) {
break;
}
String[] split = s.split(" ");
if (s.startsWith("print")) {
System.out.println(map.containsKey(split[1]) ? map.get(split[1]) : 0);
continue;
}
int x = 0;
try {
x = Integer.parse(split[1]);
} catch (Exception e) {
x = map.containsKey(split[1]) ? map.get(split[1]) : 0;
}
map.put(split[0], x);
}
}
Can somebody please explain me , why the person has used continue just after recursive call. It seems to be that the continue will not be processed because each time the recursion call will be processed.
It’s true that the recursive call will be processed — but then, eventually, the recursive call will return. (Unless it either raises an exception or enters an infinite loop, that is.) After the recursive call returns, the
continuestatement is executed.It might help you to play with a simpler example of recursion:
As you can see by running (say)
printOneToN(10), after each recursive call, control returns to its caller. A recursive call does not replace its caller.