2 115) Scanner Write a static method named wordStats that accepts as its paramet
ID: 3904855 • Letter: 2
Question
2 115) Scanner Write a static method named wordStats that accepts as its parameter a Scanner holding sequence of words and that reports the total number of words (as an integer) and the a word length (as an un-rounded double). For example, suppose the source that contains the following words: Scanner is scanningn To be or not to be, that is the question. he purposes of this problem, we will use whitespace to separate words. That his is the same definition that the means that some words include punctuation, as in "be,". (T Scanner uses for tokens.) For the inp output: ut above, your method should print exactly the following Total words 10 Average length 3.2Explanation / Answer
import java.util.Scanner;
class Main {
public static void wordStats(String text)
{
int words = 1;
int letters = 0;
// looping through each character in the given string
for(int i = 0; i<text.length(); i++)
{
// if it is a space, counting words
if(text.charAt(i) == ' ')
words++;
// otherwise counting letters
else
{
letters++;
}
}
// printing output
System.out.printf("Total words = %d ",words);
System.out.println("Average length = "+ letters/(words*1.0));
}
public static void main(String[] args) {
// taking user input and calling function
Scanner sc = new Scanner(System.in);
System.out.print("Enter text ");
String>
wordStats(one);
}
}
/*
Enter text
To be or not to be, that is the question.
Total words = 10
Average length = 3.2
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.