Results 1 to 2 of 2
- 03-05-2012, 11:58 PM #1
Member
- Join Date
- Mar 2012
- Posts
- 1
- Rep Power
- 0
Word Count That Ignores Punctuation And Space
Hi guys. I've spent a really long time writing this program and I'm incredibly stuck. The question is:
Write a program that takes a string containing a sentence or a set of sentences, and counts the number of words in the sentence that meet or exceed a specified minimum length (in letters). For example, if the minimum length entered is 4, your program should only count words that are at least 4 letters long.
Input the string and the minimum word length (integer), in that order, and output the word count (integer). Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your main program, break the input string up into words and send each one to your method.
The code I've written so far isThe problem I'm having is printing out the right "finalcount"Java Code:public class WordCount { public static void main(String[] args) { System.out.println("Enter string: "); String str = IO.readString(); System.out.println("Enter minimum length: "); int length = IO.readInt(); int wordcount = str.split("\\s+").length; int charcounter = 0; int finalcount = 0; String[] wordcount2 = str.split("\\s+"); for (int i = 0; i < str.length(); i++) { boolean isLetter = Character.isLetter(str.charAt(i)); if (isLetter) { charcounter++; if(str.length() >= length){ finalcount++; } } } System.out.println(wordcount); System.out.println(charcounter); System.out.println(finalcount); } }
If i input: cat dog elephant
and
minimum value 4
the output should be 3 words, 14 characters, 1 word.
However for finalcount, i'm getting 14.
What can I do to compare each WORD in the string to the inputted length?
Thanks
- 03-06-2012, 04:20 AM #2
Re: Word Count That Ignores Punctuation And Space
Cross posted and much discussed before this was posted here:
Word Count That Ignores Punctuation And Space - Java | Dream.In.Code
dbWhy do they call it rush hour when nothing moves? - Robin Williams
Similar Threads
-
Word Count in Java
By michaelangelokrk in forum New To JavaReplies: 4Last Post: 09-22-2011, 08:34 AM -
Count the frequency of the word in a text file instead of a sentence.
By bMorgan in forum New To JavaReplies: 3Last Post: 11-09-2010, 12:10 AM -
Count same word from many file in directory
By cassiests in forum New To JavaReplies: 4Last Post: 05-20-2010, 09:21 AM -
Count lines cointaining "word" in input file
By gwithey in forum New To JavaReplies: 5Last Post: 04-02-2009, 05:23 AM -
count occurence of word in a line of text
By sinyi88 in forum New To JavaReplies: 19Last Post: 02-28-2009, 07:37 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks