为什么要读取字母数而不是字数?

时间:2014-03-16 00:46:11

标签: java

我必须编写一个从文本文件中读取输入的程序!

Beware the Jabberwock, my son, 
the jaws that bite, the claws that catch, 
Beware the JubJub bird and shun 
the frumious bandersnatch. 

我应该打印行数,最长行,每行上的令牌数以及每行上最长令牌的长度。

我正在试图找出为什么我的代码正在读取字母数而不是字数!

Line 1 has 5 tokens (longest = 11) 
Line 2 has 8 tokens (longest = 6) 
Line 3 has 6 tokens (longest = 6) 
Line 4 has 3 tokens (longest = 13) 
Longest line : the jaws that bite, the claws that catch,

这应该是我的输出。

import java.io.*;
import java.util.*;

public class InputStats{
    public static void main (String [] args )
            throws FileNotFoundException{

        Scanner console = new Scanner ( System.in);
        System.out.println(" ");
        System.out.println();
        System.out.println("Please enter  a name of a file " );
        String name = console.nextLine();
        Scanner input = new Scanner ( new File (name));
        while (input.hasNextLine()) {
            String line = input.nextLine();
            inputStats(new Scanner(line));
        }
    }//end of amin

    public static void inputStats (Scanner input)
            throws FileNotFoundException{
        int numLines=0;
        int numwords=0;
        int Longest=0;
        String maxLine = "";

        while (input.hasNextLine()){
            String next = input.nextLine();

            numwords += next.length();
            numLines++;
        }//end of while

        System.out.print("Line " + numLines + " has ");
        System.out.print(numwords + "tokens " );
        System.out.println("(longest = " + Longest + ")");
    }//end of method
}// end of class

2 个答案:

答案 0 :(得分:1)

您将每行的长度添加到numwords计数器变量,而不是每行的字数。而不是

numwords += next.length();

您可以根据空白进行拆分

numwords += nextLine.split("\\s+").length;

答案 1 :(得分:0)

如果我理解你在寻找什么,这样的事情应该有效,

public static void inputStats(Scanner input)
      throws FileNotFoundException {
  int numLines = 0;
  int numwords = 0;
  String longest = "";
  String maxLine = "";

  while (input.hasNextLine()) {
    String nextLine = input.nextLine();
    nextLine = (nextLine != null) ? nextLine
        .trim() : "";
    if (nextLine.length() > maxLine.length()) {
      maxLine = nextLine;
    }
    StringTokenizer st = new StringTokenizer(
        nextLine);
    while (st.hasMoreTokens()) {
      String token = st.nextToken();
      token = (token != null) ? token.trim() : "";
      if (token.length() == 0) {
        continue;
      }
      numwords++;
      if (token.length() > longest.length()) {
        longest = token;
      }
    }
    numLines++;
  }// end of while
  System.out.print("Line " + numLines + " has ");
  System.out.print(numwords + "tokens ");
  System.out.println("(longest = " //
      + longest + ")");
}// end of method