Stewie Griffin Stewie Griffin - 5 months ago 14x
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(;

public static int count(Scanner input) {

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


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.