【问题标题】:Counting words using the Scanner.next() method使用 Scanner.next() 方法计算单词
【发布时间】:2019-03-08 19:14:22
【问题描述】:

我目前正在研究一种方法,该方法必须返回 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} 的数组。

【问题讨论】:

  • 这个问题被否决了,因为它太宽泛了。拿起tour 并阅读How to Ask,稍后再回来。
  • 所以,您已经说明了您希望您的程序做什么,并且您已经向我们展示了您到目前为止所做的事情,但您实际上还没有提出编程问题。到目前为止,你还没有向我们展示你已经尝试过什么,也没有给出任何关于你坚持什么的迹象。您在编写字数统计代码时遇到了哪些具体问题?
  • 我刚刚更新了我的帖子并试图使其更具体,这是我第一次发帖,所以如果我过于宽泛或没有提出正确的问题,我深表歉意。

标签: java arrays string java.util.scanner


【解决方案1】:

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

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

您可以使用布尔值 isEndWord 在单词结束时触发。

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 2012-05-06
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多