Write the definition of a method named count that receives a reference to a Scan
ID: 650376 • Letter: W
Question
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.
It must be done recursively with Java.
Explanation / Answer
Commnet if you have any doubts.
public static int countWords(Scanner input)
{
if(input.hasNext())
{
input.next();
return 1+countWords(input);
}
else return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.