In: Computer Science
Instructions
Today, all input and output has been taken care of for you. All you need to do is finish off the function wordCount that calculates the number of words in a string.
Function Details
Input
Processing
/** * wordCount (String) -> int * Calculates the number of words in a given string * @param ?? (str): String of words * @return Number of words in the string (int) */
The method takes in a string. It then calculates the the number
of words in that string and returns that value.
HINT: This can be done by first splitting the string into individual words using the String.split() method. Then you just need to count how many objects the array holds (and there is an array method for that as well!
Output
Sample input/output:
use JAVA method complete this question
Input | Output |
I have really enjoyed teaching this class and all of you! |
Word count: 11 |
I am designing a test and do not want to get bogged down in what the text actually says. |
Word count: 19 |
Program
filename: WordCount.java
public class WordCount{
/**
* wordCount (String) -> int
* Calculates the number of words in a given string
* @param inputString String of words
* @return Number of words in the string (int)
*/
public static int wordCount(String inputString) {
int count = 0;
int inWord = 0;
for (char letter : inputString.toCharArray()) {
//non-space means were "in a word"
if (letter != ' ') {
inWord = 1;
} else {
// space is the delimiter, but we only want to count a word
if
// we were previously "in a word"
if (inWord == 1) {
count++;
inWord = 0;
}
}
}
// Just in case we were "in a word," but never encountered another
space
if (inWord == 1) {
count++;
}
return count;
}
public static void main(String args[]){
String input = "I have really enjoyed teaching this class and all
of you!";
System.out.println("wordCount(\"I have really enjoyed teaching this
class and all of you!\") : " + wordCount(input));
}
}
Output
==========================================================================================
Hope this helps!
Please let me know if any changes needed.
Thank you!
I hope you're safe during the pandemic.