Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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.2

Explanation / 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

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote