【问题标题】:count characters, words and lines in file计算文件中的字符、单词和行数
【发布时间】:2013-08-16 13:23:37
【问题描述】:

这应该计算文件中的行数、单词数和字符数。

但它不起作用。从输出中它只显示0

代码:

public static void main(String[] args) throws IOException {
    int ch;
    boolean prev = true;        
    //counters
    int charsCount = 0;
    int wordsCount = 0;
    int linesCount = 0;

    Scanner in = null;
    File selectedFile = null;
    JFileChooser chooser = new JFileChooser();
    // choose file 
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        selectedFile = chooser.getSelectedFile();
        in = new Scanner(selectedFile);         
    }

    // count the characters of the file till the end
    while(in.hasNext()) {
        ch = in.next().charAt(0);
        if (ch != ' ') ++charsCount;
        if (!prev && ch == ' ') ++wordsCount;
        // don't count if previous char is space
        if (ch == ' ') 
            prev = true;
        else 
            prev = false;

        if (ch == '\n') ++linesCount;
    }

    //display the count of characters, words, and lines
    charsCount -= linesCount * 2;
    wordsCount += linesCount;
    System.out.println("# of chars: " + charsCount);
    System.out.println("# of words: " + wordsCount);
    System.out.println("# of lines: " + linesCount);

    in.close();
}

我不明白发生了什么。 有什么建议吗?

【问题讨论】:

  • charsCountwordsCountlinesCount 是否显示 0?还是仅对其中一个显示 0?
  • 请注意,while 循环内的ch 永远不会等于' ''\n'。扫描程序的默认分隔符是为 Character.isWhitespace 返回 true 的字符。因此,hasNext 方法将跳过该类别下的所有字符。
  • @Joffutt 它显示每个0

标签: java count output


【解决方案1】:

不同的方法。使用字符串查找行数、单词数和字符数:

public static void main(String[] args) throws IOException {
        //counters
        int charsCount = 0;
        int wordsCount = 0;
        int linesCount = 0;

        Scanner in = null;
        File selectedFile = null;
        JFileChooser chooser = new JFileChooser();
        // choose file 
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            selectedFile = chooser.getSelectedFile();
            in = new Scanner(selectedFile);
        }

        while (in.hasNext()) {
            String tmpStr = in.nextLine();
            if (!tmpStr.equalsIgnoreCase("")) {
                String replaceAll = tmpStr.replaceAll("\\s+", "");
                charsCount += replaceAll.length();
                wordsCount += tmpStr.split(" ").length;
            }
            ++linesCount;
        }

        //display the count of characters, words, and lines
        System.out.println("# of chars: " + charsCount);
        System.out.println("# of words: " + wordsCount);
        System.out.println("# of lines: " + linesCount);

        in.close();
    }


注意:
对于其他编码样式,使用new Scanner(new File(selectedFile), "###"); 代替new Scanner(selectedFile);

### 是需要的字符集。参考thiswiki

【讨论】:

  • 具体是什么? @nazar_art
  • 输出:# of chars: 0 # of words: 0 # of lines: 0
  • 那文件一定是空的吧? @nazar_art
  • 我认为这适用于所有情况,但不确定...您能提供所用测试文件的快照吗?...@nazar_art
  • @nazar_art :我认为this 可能会有所帮助。
【解决方案2】:

您的代码仅查看文件中默认标记(单词)的第一个字符。

当您执行此操作ch = in.next().charAt(0) 时,它会为您获取令牌(单词)的第一个字符,并且扫描器会向前移动到下一个令牌(跳过该令牌的其余部分)。

【讨论】:

    【解决方案3】:

    这里有几个问题。

    首先是对行尾的测试会导致问题,因为它通常不是表示行尾的单个字符。阅读http://en.wikipedia.org/wiki/End-of-line 了解有关此问题的更多详细信息。

    单词之间的空白字符可以不仅仅是 ASCII 32(空格)值。将选项卡视为一种情况。您想检查 Character.isWhitespace() 的可能性更大。

    您还可以使用How to check the end of line using Scanner? 中的两个扫描仪解决行尾问题

    这里是您提供的代码以及输入和输出的快速破解。

    import java.io.*;
    import java.util.Scanner;
    import javax.swing.JFileChooser;
    
    public final class TextApp {
    
    public static void main(String[] args) throws IOException {
        //counters
        int charsCount = 0;
        int wordsCount = 0;
        int linesCount = 0;
    
        Scanner fileScanner = null;
        File selectedFile = null;
        JFileChooser chooser = new JFileChooser();
        // choose file 
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            selectedFile = chooser.getSelectedFile();
            fileScanner = new Scanner(selectedFile);         
        }
    
        while (fileScanner.hasNextLine()) {
          linesCount++;
          String line = fileScanner.nextLine();
          Scanner lineScanner = new Scanner(line);
          // count the characters of the file till the end
          while(lineScanner.hasNext()) {
            wordsCount++;
            String word = lineScanner.next();
            charsCount += word.length();
          } 
    
        lineScanner.close();
      }
    
      //display the count of characters, words, and lines
      System.out.println("# of chars: " + charsCount);
      System.out.println("# of words: " + wordsCount);
      System.out.println("# of lines: " + linesCount);
    
      fileScanner.close();
     }
    }
    

    这里是测试文件输入:

    $ cat ../test.txt 
    test text goes here
    and here
    

    这是输出:

    $ javac TextApp.java
    $ java TextApp 
    # of chars: 23
    # of words: 6
    # of lines: 2
    $ wc test.txt 
     2  6 29 test.txt
    

    字符数之间的差异是由于没有计算空白字符,这似乎是您在原始代码中尝试执行的操作。

    希望对你有所帮助。

    【讨论】:

      【解决方案4】:

      您可以将每一行存储在List<String> 中,然后是linesCount = list.size()

      计算charsCount:

      for(final String line : lines)
          charsCount += line.length();
      

      计算wordsCount

      for(final String line : lines)
          wordsCount += line.split(" +").length;
      

      将这些计算结合在一起而不是单独进行可能是一个明智的主意。

      【讨论】:

        【解决方案5】:

        使用Scanner 方法:

        int lines = 0;
        int words = 0;
        int chars = 0;
        while(in.hasNextLine()) {
            lines++;
            Scanner lineScanner = new Scanner(in.nextLine());
            lineScanner.useDelimiter(" ");
            while(lineScanner.hasNext()) {
                words++;
                chars += lineScanner.next().length();
            }
        }
        

        【讨论】:

        • 默认的 Scanner 分隔符已经是在传递给 true 时返回 true 的字符。
        【解决方案6】:

        似乎每个人都在建议您另一种选择,

        您的逻辑的缺陷是,您没有遍历整行的所有字符。您只是在遍历每一行的第一个字符。

         ch = in.next().charAt(0);
        

        另外,charsCount -= linesCount * 2; 中的 2 代表什么?

        您可能还想在访问文件时包含一个 try-catch 块。

          try {
                    in = new Scanner(selectedFile);
                } catch (FileNotFoundException e) {}
        

        【讨论】:

        • 在 charAt(0) 错误上很好地捕获 JNL。我避开了它。我假设他用 charsCount 删除了 CR+LF 字符。
        【解决方案7】:

        也许我的代码会帮助你...一切正常

        import java.io.BufferedReader;
        import java.io.File;
        import java.io.FileReader;
        import java.io.IOException;
        import java.util.Scanner;
        import java.util.StringTokenizer;
        
        public class LineWordChar {
            public static void main(String[] args) throws IOException {
                // Convert our text file to string
            String text = new Scanner( new File("way to your file"), "UTF-8" ).useDelimiter("\\A").next();
            BufferedReader bf=new BufferedReader(new FileReader("way to your file"));
            String lines="";
            int linesi=0;
            int words=0;
            int chars=0;
            String s="";
            // while next lines are present in file int linesi will add 1
                while ((lines=bf.readLine())!=null){
                linesi++;}
            // Tokenizer separate our big string "Text" to little string and count them
            StringTokenizer st=new StringTokenizer(text);
             while (st.hasMoreTokens()){
                `enter code here`  s = st.nextToken();
                  words++;
            // We take every word during separation and count number of char in this words    
                  for (int i = 0; i < s.length(); i++) {
                      chars++;}
                }
             System.out.println("Number of lines: "+linesi);
             System.out.println("Number of words: "+words);
             System.out.print("Number of chars: "+chars);
         }
        }
        

        【讨论】:

          【解决方案8】:
          public class WordCount {
          
              /**
               * @return HashMap a map containing the Character count, Word count and
               *         Sentence count
               * @throws FileNotFoundException 
               *
               */
              public static void main() throws FileNotFoundException {
                  lineNumber=2; // as u want
                  File f = null;
                  ArrayList<Integer> list=new ArrayList<Integer>();
          
                  f = new File("file.txt");
                  Scanner sc = new Scanner(f);
                  int totalLines=0;
                  int totalWords=0;
                  int totalChars=0;
                  int totalSentences=0;
                  while(sc.hasNextLine())
                  {
                      totalLines++;
                      if(totalLines==lineNumber){
                          String line = sc.nextLine();
                          totalChars += line.length();
                          totalWords += new StringTokenizer(line, " ,").countTokens();  //line.split("\\s").length;
                          totalSentences += line.split("\\.").length;
                          break;
                      }
                      sc.nextLine();
          
                  }
          
                  list.add(totalChars);
                  list.add(totalWords);
                  list.add(totalSentences);
                  System.out.println(lineNumber+";"+totalWords+";"+totalChars+";"+totalSentences);
          
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2023-03-12
            • 2018-06-02
            • 1970-01-01
            • 2013-02-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-02-20
            • 2023-03-16
            相关资源
            最近更新 更多