Stewie Griffin Stewie Griffin - 6 months ago 17
Java Question

Counting the number of strings remaining to be read in standard input using recursion

I want to write a method that has a Scanner parameter associated with a stream of input and counts the number of Strings within the input. However, I have a stack overflow exception. Can you tell me the reason? Thank you a lot.

import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(count(input));
}

public static int count(Scanner input) {

if (input.hasNextLine())
return 1 + count(input);
else
return 1;
}
}

Answer

You need to call nextLine() on input in the line return 1 + count(input). You are checking for the next line, but nothing actually consumes it. This means the Scanner never runs out of lines to process.