java - 使用扫描仪评估字符串中的单词

标签 java java.util.scanner

我正在尝试编写一个方法,该方法从“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/

相关文章:

c# - 是否可以在 C++ 中序列化和反序列化对象?

java - 当PK删除不存在的数据时,如何处理Spring Data JPA删除?

java - 如何从字符串中获取多个字符?

java - 如何保留字符串中所有出现的特定字符(不区分大小写)并使所有非字母字符不受影响?

java - 获取输入时扫描仪抛出 java.util.NoSuchElementException

java - 我如何为访问 n 个教会的 n 个牧师制定时间表?

java - 按扩展名列出和计数文件

java - 如果是字符串,则保存到变量;否则,忽略其余的和下一行

java - 从txt文件中读取整数并存储到数组中

java - 返回文本文件中单词出现的所有行号的方法