155k views
5 votes
Write the definition of a method named count that receives a reference to a Scanner object associated with a stream of input. The method reads all the Strings remaining to be read in standard input and returns their count (that is, how many there are) So if the input were: hooligan sausage economy ruin palatial the method would return 5 because there are 5 Strings there. The method must not use a loop of any kind (for, while, do-while) to accomplish its job.

1 Answer

3 votes

Answer and Explanation:

CountInput.java

import java.util.Scanner;

public class CountInput {

public int count(Scanner in)

{

int inputStringCount = 0;

if (in.hasNext())

{

in.next();

return 1 + count(in);

}

return inputStringCount;

}

public static void main(String[] args)

{

CountInput countInput = new CountInput();

Scanner in = new Scanner(System.in);

int inputStringCount = countInput.count(in);

System.out.println("Read " + inputStringCount + " strings from input.");

in.close();

}

}

Sample run:

$ java CountInput

hooligan sausage economy

ruin palatial

Read 5 strings from input.

User Busata
by
6.2k points