【问题标题】:Read a text file and count the number of white spaces in the text file读取文本文件并计算文本文件中空格的数量
【发布时间】:2021-09-26 02:58:00
【问题描述】:

我需要我的 Java 程序来获取一个文本文件,读取该文本文件,计算并重现该文本文件中的空白数量

这是我目前拥有的代码

import java.io.File;  //import the file class
import java.io.FileNotFoundException; //import this class to handle errors
import java.util.Scanner; //import the scanner class to read the file

public class whitespaceReader {

    public static void main(String[] args) {
        try {

            File myFile = new File("aliceInWonderland.txt");

            Scanner reader = new Scanner(myFile);

            int space = 0;
            int i = 0;
            String word;

            word = reader.nextLine();

            while (i < word.length()){
                char a = word.charAt(i);

                if(a == '//tried to use empty brackets here, did not work') {
                    space++;
                }
                i++;
            }
            System.out.println("amount of white space is: " + space);

        } catch (FileNotFoundException e) {
            System.out.print("Uh oh! Something went wrong");
            e.printStackTrace();
        }
    }
}

【问题讨论】:

  • 您需要仔细阅读作业要求,才能准确理解老师所说的“空白”是什么意思。这是否仅表示 SP 字符? TAB(又名HT)或VT呢? CRNL 呢?不间断的空间代码呢?另外,找出TAB 是否正好表示一个“空白”,如果CR NL 表示一个或两个“空白”。
  • 但如果您需要计算SP 个字符,那么a == ' ' 就可以了。 (单)引号之间正好是一个空格字符。
  • 分配要求没有指定任何这些定义,它只是说计算空白。我以为它的意思是在单词之间?但细节很少。
  • 那么你需要>>问你的老师他或她的意思。或者做一个猜测,希望你猜对了。
  • 谢谢您,非常感谢您的帮助。我将通过教程进行澄清,您的建议对单引号之间的一个空格字符非常有帮助!

标签: java whitespace


【解决方案1】:

你可以这样做

public static void main(String[] args) {
    try {

        File myFile = new File("aliceInWonderland.txt");

        Scanner reader = new Scanner(myFile);

        int space = 0;
        int n = 0;
        String word = "";

        while(reader.hasNextLine()){
            word += reader.nextLine();
        }
        n = word.length();

        space = word.replace(" ","").length();
        space = n - space;
        System.out.println("amount of white space is: " + space);

    } catch (FileNotFoundException e) {
        System.out.print("Uh oh! Something went wrong");
        e.printStackTrace();
    }
}

你只需要用没有空格的句子长度减去句子的长度。

不需要循环

【讨论】:

    【解决方案2】:

    使用 BufferedReader 来读取这样的行。

    final String fileName = "Path to your file"
    final char countedChar = ' ';
    int characterCount = 0;
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    String line = null;
    while((line = br.readLine()) != null){
     for(int i = 0; i < line.length(); i++){
       if(countedChar == line.charAt(i)){
         characterCount++;
       }
     }
    }
    System.out.println(characterCount);
    

    【讨论】:

      【解决方案3】:

      如果您使用java.util.Scanner 类并且只计算空格字符,即Unicode 代码点为32(十进制)的字符,并且您至少使用JDK 9,那么您可以简单地调用方法@987654321 @ 并计算该方法返回的流中元素的数量。

      import java.io.IOException;
      import java.nio.file.Path;
      import java.nio.file.Paths;
      import java.util.Scanner;
      
      public class WhitespaceReader {
      
          public static void main(String[] args) {
              Path path = Paths.get("aliceInWonderland.txt");
              try (Scanner reader = new Scanner(path)) {
                  long space = reader.findAll(" ")
                                     .count();
                  System.out.println("amount of white space is: " + space);
              }
              catch (IOException xIo) {
                  xIo.printStackTrace();
              }
          }
      }
      

      注意上面的代码使用try-with-resources来保证Scanner是关闭的,以防止资源泄漏。

      另外请注意,我将类名更改为WhitespaceReader,以便坚持java naming conventions

      如果要计算所有whitespace 字符,只需将字符串参数(方法findAll)更改为\\s+。类java.util.regex.Pattern

      参考javadoc

      【讨论】:

        最近更新 更多