简体   繁体   English

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

[英]Counting words using the Scanner.next() method

I am currently working on a method that has to return the number of newline characters, words, and characters of a string in an int[] array.我目前正在研究一种方法,该方法必须返回 int[] 数组中字符串的换行符、单词和字符数。 I am confused on how count the number of times the Scanner.next() method runs.我对如何计算 Scanner.next() 方法运行的次数感到困惑。 I have tried to use an if statement like this:我曾尝试使用这样的 if 语句:

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

but I get java.util.NoSuchElementException.但我得到 java.util.NoSuchElementException。 How would I get around the NoSuchElementException and count the tokens instead of returning them?我将如何解决 NoSuchElementException 并计算令牌而不是返回它们? Here is what I have so far:这是我到目前为止所拥有的:

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.");
}

The test should return an array of {1, 5, 25}.测试应返回一个 {1, 5, 25} 数组。

For checking the amount of word in a string, you will need to check if the next character is a letter.要检查字符串中的单词数量,您需要检查下一个字符是否是字母。 At the same time, you will need a condition to check if it is end of the word.同时,您将需要一个条件来检查它是否是单词的结尾。

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++;
   }
}

You can used the boolean isEndWord to trigger whenever the word ends.您可以使用布尔值 isEndWord 在单词结束时触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM