使用Scanner.next()方法对单词计数

时间:2019-03-08 19:14:22

标签: java arrays string java.util.scanner

我目前正在研究一种方法,该方法必须返回int []数组中的换行符,单词和字符串的字符数。我对如何计算Scanner.next()方法运行的次数感到困惑。我尝试使用如下if语句:

if (!(in.next() == (""))) { words++; }

但是我得到了java.util.NoSuchElementException。我如何绕过NoSuchElementException并计算令牌而不是返回令牌?这是我到目前为止的内容:

import java.util.Scanner;

public class WordCount {

/**
 * Scans a string and returns the # of newline characters, words, and
 * characters in an array object.
 * 
 * @param text string to be scanned
 * @return # of newline characters, words, and characters
 */
public static int[] analyze(String text) {
    // Variables declared
    Scanner in = new Scanner(text);
    int[] values = new int[3];
    int line = 0;
    int words = 0;
    int characters = 0;

    // Checks string for # of newlines, chars, and words
    for (int i = 0; i < text.length(); i++) {
        char n = text.charAt(i);

        if (n == '\n') {
            line++;
        }
        if (in.hasNext()) {
            characters++;
        }

        //this is where I think the word count statement should go

    }
    values[0] = line;
    values[1] = words;
    values[2] = characters;
    return values;
}

public static void main(String[] args) {
    analyze("This is\n a test sentence.");
}

测试应返回{1,5,25}的数组。

1 个答案:

答案 0 :(得分:0)

要检查字符串中单词的数量,您需要检查下一个字符是否为字母。同时,您将需要一个条件来检查它是否是单词的结尾。

boolean isEndWord = false;
// Checks string for # of newlines, chars, and words
for (int i = 0; i < text.length(); i++) {
   char n = text.charAt(i);
   if ((!Character.isLetter(n))&&isEndWord == true) {
      words++;
      isEndWord = false;
   }
   if (n == ' ') {
      isEndWord = true;
   }
   if (n == '\n') {
       line++;
       isEndWord = true;
   }
   if (in.hasNext()) {
       characters++;
   }
}

您可以使用boolean isEndWord在单词结束时触发。