简体   繁体   English

使用扫描仪扫描仪(Java)计算字数和行数

[英]Counting words and lines using scanner Scanner (Java)

This is my first time here at stackoverflow and sometimes tells me that i will be here quite a lot of times soon xD. 这是我第一次在Stackoverflow上,有时告诉我xD很快就会出现在这里。

I'm trying to do a pretty simple thing, counting the number of words and the number of lines of a text given by the user using through a Scanner(Obviously with an unknown number of words and lines), and finally printing these 2 numbers. 我正在尝试做一个非常简单的事情,计算用户使用Scanner给定的单词数和文本行数(显然是未知的单词和行数),最后打印出这两个数字。 All this using Java. 所有这些都使用Java。

For now I've been trying for a few days to do the word count part(Since after doing this it would be very similar to code the lines part). 现在,我已经尝试了几天来做单词计数部分(因为这样做之后,将非常类似于对行部分进行编码)。 I've tried a lot of things using arrays, split methods, etc. Now I have this code: 我已经尝试了很多使用数组,拆分方法等的方法。现在我有了以下代码:

import java.util.Locale;
import java.util.Scanner;
import java.util.regex.Pattern;

public class WordCount {
     public static void main(String[] args) {

         int i=0;

         Scanner input = new Scanner(System.in).useLocale(Locale.US);

         while(input.hasNextLine()) {
            i++;
            input.next();
            }

         System.out.printf("%30s\n", "The text has " + i + " words");
     }
}

This count correctly the words in the text, however, since the while loop never ends, it never prints the total number of words and neither will continue with the following code when I write it. 这样可以正确计算文本中的单词,但是,由于while循环永远不会结束,因此它永远不会打印单词的总数,并且在我编写时都不会继续下面的代码。

Can someone help me solving this problem? 有人可以帮我解决这个问题吗?

Thanks in advance! 提前致谢!

Have a good day! 祝你有美好的一天!

I would tweak your code to the following : 我会将您的代码调整为以下内容:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in).useLocale(Locale.US);

    int lines = 0;
    int words = 0;

    String currLine = "?"; 
    while (currLine != null && currLine.trim().length() > 0) {
        currLine = input.nextLine();
        words = words + currLine.split("\\W+").length;
        lines++;
    }

    System.out.printf("%30s\n", "The text has " + (lines - 1) + " lines");
    System.out.printf("%30s\n", "The text has " + (words - 1) + " words");
    input.close();    
}
  • We need to use a variable to hold the input so I've used currLine to hold each line entered by the user. 我们需要使用一个变量来保存输入,因此我使用了currLine来保存用户输入的每一行。
  • Rename the variables to lines and word accordingly. 将变量重命名为lines和相应的word
  • Use a regex to split each word and then calculate the length of the array and finally store it in words. 使用regex拆分每个单词,然后计算数组的长度,最后将其存储在单词中。

As soon as the user enters a blank line the program terminates. 用户一旦输入空白行,程序就会终止。

Output : 输出:

asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd

The text has 1 lines 文字有1行

The text has 8 words 文字有8个字

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

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