Issue
Im trying to write a method that returns the number of words from the "words" parameter that have at least the min" but no more than the "max c"haracters.
public static int countWords(String words, int min, int max)
{
Scanner s = new Scanner (words);
int counter = 0;
while (s.hasNext())
{
String word = s.next();
int wordLength = word.length();
if (wordLength>min && wordLength<max)
{
counter= counter + 1;
s.close();
}
}
return counter;
}
Solution
Based on what I can understand from you, you want to count words that has specified max and min
For example,
"The rain in Spain falls mainly in the plain", 3, 5
is return 5
because they are 3 fives and 2 threes
your code is quite alright except this part which needs some change in its logic
if (wordLength>min && wordLength<max)
Based on what I understand from your question you want word which has either min length or max length
As result you have to change that if statement to this
if (wordLength == min || wordLength == max) {
Explanation : length of the word is equal to min length or max length , counter is gonna be added
Answered By - Kick Buttowski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.