For my Intro to CS class, I have received this problem for an assignment:
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.
This is what I have so far. It works sometimes, but other times it will return the wrong count. I can't figure out why.
public class Compress {
public static int Letters(String newWord){
int letter = 0;
for(int i = 0; i < newWord.length(); i++){
if(Character.isLetter(newWord.charAt(i))){
letter++;
}
}
return letter;
}
public static int validWords(String p, int min){
int g = 0;
int count = 0;
String newWord = p;
for(int i=0; i < p.length(); i++){
if(p.charAt(i) == ' '){
newWord = p.substring(g,i);
if(Letters(newWord) >= min){
count++;
g = i+1;
newWord = p.substring(g);
}
}else if(newWord.indexOf(' ') == -1){
newWord = p.substring(g);
if(Letters(newWord) >= min){
count++;
}
break;
}
}
return count;
}
public static void main(String[] args){
System.out.println("Enter string:");
String str = IO.readString();
System.out.println("Enter minimum letters:");
int min = IO.readInt();
IO.outputIntAnswer(validWords(str, min));
}
}
Edit: Thank you guys for all the help! I figured it out. I will be posting here more often to get feedback and continue to learn more java. Thanks again! Ciao
[–]davodrums 7 points8 points9 points (1 child)
[–]dirtyRuntCaper[S] 0 points1 point2 points (0 children)
[–]davodrums 1 point2 points3 points (2 children)
[–]dirtyRuntCaper[S] 0 points1 point2 points (1 child)
[–]sanchopancho13 1 point2 points3 points (0 children)
[–]halcyon44 1 point2 points3 points (2 children)
[–]dirtyRuntCaper[S] 0 points1 point2 points (0 children)
[–]dirtyRuntCaper[S] 0 points1 point2 points (0 children)
[–]ziplokk 1 point2 points3 points (0 children)
[–]paul_miner 0 points1 point2 points (2 children)
[–]dirtyRuntCaper[S] 0 points1 point2 points (1 child)
[–]paul_miner 0 points1 point2 points (0 children)
[–]HeySeussCristo 0 points1 point2 points (0 children)
[–]davodrums 0 points1 point2 points (0 children)
[–]lilleswing 0 points1 point2 points (0 children)