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

mming Exercise 7-5 Instructions countWords java+ 1 tnport java.uttl.* 2 public c

ID: 3747183 • Letter: M

Question

mming Exercise 7-5 Instructions countWords java+ 1 tnport java.uttl.* 2 public class Counthords [ 8 public static void main(S Write an application that counts the words in a string entered by a user. Words are separated by any combination of spaces, periods, commas, semicolons, question marks, exclamation points, or dashes. Figure 7-17 shows a typical execution. nter a string Lions! And Tigers! And bears!...Oh my here are 7 words in the string Figure 7-17 Typical execution of the Countwords application Grading Write your Java code in the area on the right. Use the Run button to compile and run the code. Clicking the Run Checks button will run pre-configured tests against your code to calculate a grade. Once you are happy with your results, click the Submit button to record your score.

Explanation / Answer

package chapter_8_3026chegg;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Chapter_8_3026Chegg {

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{

Scanner in =new Scanner(System.in);
System.out.println("Enter the line");
String s=in.nextLine();
String tm="";
//store word count in res
int res=0;
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
//If character is alphabet append it on temporary string
if(i==s.length()-1&&tm.length()>0)
res++;
if(Character.isLetter(c)){
tm=tm+c;
}
else{
//If string has some length then increment the word count
if(tm.length()>0)
res++;
//make empty string
tm="";
}
  
}
System.out.println("The word count in "+s+" is :"+res);
}
  
}