我正在尝试编写一个方法,该方法从“words”参数返回至少具有“min”但不超过“max c”字符的单词数。
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;
}
最佳答案
只是一个小小的改变。您正在 while 循环中关闭扫描仪,将其移出循环即可工作。
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;
}
我还建议,您更改 if 条件以使其包含最小值和最大值。 if (wordLength >= min && wordLength =< max) { 例如,countWords("count Words in this line 1 22 333 4444 55555",3,4) 不会为当前条件下的任何字符串返回任何结果。
关于java - 使用扫描仪评估字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25778963/