ComputerScienceExpert

(11)

$18/per page/

About ComputerScienceExpert

Levels Tought:
Elementary,Middle School,High School,College,University,PHD

Expertise:
Applied Sciences,Calculus See all
Applied Sciences,Calculus,Chemistry,Computer Science,Environmental science,Information Systems,Science Hide all
Teaching Since: Apr 2017
Last Sign in: 103 Weeks Ago, 3 Days Ago
Questions Answered: 4870
Tutorials Posted: 4863

Education

  • MBA IT, Mater in Science and Technology
    Devry
    Jul-1996 - Jul-2000

Experience

  • Professor
    Devry University
    Mar-2010 - Oct-2016

Category > Programming Posted 26 May 2017 My Price 9.00

public class task4

import java.util.Scanner;

public class task4
{
  
  
  public static void main(String[] args) 
  {
    Scanner in = new Scanner(System.in);
    
    while (true)
    {
      System.out.printf("Enter some text, or q to quit: ");
      String text = in.nextLine();
      if (text.equals("q"))
      {
        System.out.printf("Exiting...n");
        break;
      }
      int result = count_words(text);
      System.out.printf("Counted %d words.nn", result);
    }
  }
}

This is an incomplete program. The goal of the program is to take as input sentences from the user, and then print out the number of words in each sentence. Complete that program, by defining acount_wordsfunction, that satisfies the following specs:

  • Functioncount_wordstakes one argument, calledtext, which is a string, and which is allowed to contain only uppercase letters, lowercase letters, and the space character ' '. In other words, don't worry about handling cases cases wheretextcontains characters that are punctuation, special symbols, or anything else that is not a letter or the space character.
  • Functioncount_wordscounts and returns the number of words intext.

The strategy for counting words is simple:

  1. You initialize your counter to zero if your text starts with a space character, or to 1 if your text starts with a letter.
  2. You go through the text, character by character. You increment your counter every time you find a letter whose previous character was space. For example, if your current character is 'm' and the previous character was ' ', it means that you have found a new word.

It may be that the text starts with multiple spaces, or that multiple spaces are placed between two words. Your code should handle that correctly.

IMPORTANT: you are NOT allowed to modify in any way the main function.

This is an example run of the complete program:

Enter some text, or q to quit: this is the fourth week of the semester
Counted 8 words.

Enter some text, or q to quit:     hello world
Counted 2 words.

Enter some text, or q to quit: 
Counted 0 words.

Enter some text, or q to quit:     h    hhg
Counted 2 words.

Enter some text, or q to quit: q
Exiting...

Answers

(11)
Status NEW Posted 26 May 2017 03:05 AM My Price 9.00

-----------

Not Rated(0)