2013-03-06 160 views
4

我想從用戶處獲取輸入,並在文本文件中輸出行數,字數和字符數。但是,只有字數是正確的,它總是爲行和字符打印0。計算文本文件中的行數,字數和字符數

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

public class TextFileInfoPrinter 
{ 
    public static void main(String[]args) throws FileNotFoundException   
    { 
      Scanner console = new Scanner(System.in);   

      System.out.println("File to be read: "); 
      String inputFile = console.next(); 

      File file = new File(inputFile); 
      Scanner in = new Scanner(file); 

      int words = 0; 
      int lines = 0; 
      int chars = 0; 

      while(in.hasNext()) 
      { 
       in.next(); 
       words++; 
      } 

      while(in.hasNextLine()) 
      { 
       in.nextLine(); 
       lines++; 
      } 

      while(in.hasNextByte()) 
      { 
       in.nextByte(); 
       chars++; 
      } 

      System.out.println("Number of lines: " + lines); 
      System.out.println("Number of words: " + words); 
      System.out.println("Number of characters: " + chars); 
    } 
} 

回答

2

in.next();正在消耗第一個while()中的所有行。在第一個while循環結束後,輸入流中不會再有字符被讀取。

你應該巢穴你的性格和字數一個while循環計數線。

1

是有一些原因,你認爲:

while(in.hasNext()) 
{ 
    in.next(); 
    words++; 
} 

消耗整個輸入流?

這樣做,這意味着您的其他兩個while循環將永遠不會迭代。這就是爲什麼你的單詞和行的值仍然設置爲零。

您可能最好每次讀取一個字符的文件,每次循環增加字符數,並檢測字符以決定是否增加其他計數器。

基本上,無論你找到一個\n,增加行數 - 你應該也可能這樣做,如果流中的最後一個字符不是\n

而且,無論何時從白空間過渡到非空白空間,都要增加字數(可能會在流開始處理一些棘手的邊緣情況處理,但這是一個實現問題)。

您正在尋找類似下面的僞代碼:執行第一而當

# Init counters and last character 

charCount = 0 
wordCount = 0 
lineCount = 0 
lastChar = ' ' 

# Start loop. 

currChar = getNextChar() 
while currChar != EOF: 
    # Every character counts. 

    charCount++; 

    # Words only on whitespace transitions. 

    if isWhite(lastChar) && !isWhite(currChar): 
     wordCount++ 

    # Lines only on newline characters. 

    if currChar == '\n': 
     lineCount++; 
    lastChar = currChar 
    currChar = getNextChar() 

# Handle incomplete last line. 

if lastChar != '\n': 
    lineCount++; 
0

文件指針設置爲文件的末尾。試試這個:

Scanner in = new Scanner(file); 


     while(in.hasNext()) 
     { 
      in.next(); 
      words++; 
     } 
     in = new Scanner(file); 
     while(in.hasNextLine()) 
     { 
      in.nextLine(); 
      lines++; 
     } 
     in = new Scanner(file); 
     while(in.hasNextByte()) 
     { 
      in.nextByte(); 
      chars++; 
     } 
+0

的工作,但不正確的做法IMO – 2013-03-06 05:08:37

+0

築巢它將有其自身的問題。條件需要改變。 – Aashray 2013-03-06 05:10:13

0

我不是Java專家,但我會推定該.hasNext.hasNextLine.hasNextByte全部使用,並增加相同的文件位置指示器。您需要重置該設置,或者通過創建一個新的掃描器作爲Aashray提到的方法,或者使用RandomAccessFile並在每個循環之後調用file.seek(0);

6

嘗試

int words = 0; 
    int lines = 0; 
    int chars = 0; 
    while(in.hasNextLine()) { 
     lines++; 
     String line = in.nextLine(); 
     chars += line.length(); 
     words += new StringTokenizer(line, " ,").countTokens(); 
    } 
+0

謝謝,這有助於 – user2138453 2013-03-06 05:21:58

+0

好,請注意,我們可以以不同的方式計算單詞,我用','和''作爲單詞分隔符,但您可以更改它 – 2013-03-06 05:25:36

0

我@Cthulhu答案達成一致。在您的代碼中,您可以重置您的Scanner對象(in)。

in.reset(); 

這會在您的文件的第一行重置您的對象。

0

您可以使用正則表達式來計算。

String subject = "First Line\n Second Line\nThird Line"; 
Matcher wordM = Pattern.compile("\\b\\S+?\\b").matcher(subject); //matches a word 
Matcher charM = Pattern.compile(".").matcher(subject); //matches a character 
Matcher newLineM = Pattern.compile("\\r?\\n").matcher(subject); //matches a linebreak 

int words=0,chars=0,newLines=1; //newLines is initially 1 because the first line has no corresponding linebreak 

while(wordM.find()) words++; 
while(charM.find()) chars++; 
while(newLineM.find()) newLines++; 

System.out.println("Words: "+words); 
System.out.println("Chars: "+chars); 
System.out.println("Lines: "+newLines); 
0
while(in.hasNextLine()) { 
     lines++; 
     String line = in.nextLine(); 
     for(int i=0;i<line.length();i++) 
     { 
      if(line.charAt(i)!=' ' && line.charAt(i)!='\n') 
     chars ++; 
     } 
     words += new StringTokenizer(line, " ,;:.").countTokens(); 
    } 
1

我認爲最好的答案是

int words = 0; 
int lines = 0; 
int chars = 0; 
while(in.hasNextLine()) { 
    lines++; 
    String line = in.nextLine(); 
    for(int i=0;i<line.length();i++) 
    { 
     if(line.charAt(i)!=' ' && line.charAt(i)!='\n') 
     chars ++; 
    } 
    words += new StringTokenizer(line, " ,").countTokens(); 
} 
0
import java.io.*; 
class wordcount 
{ 
    public static int words=0; 
    public static int lines=0; 
    public static int chars=0; 
    public static void wc(InputStreamReader isr)throws IOException 
    { 
     int c=0; 
     boolean lastwhite=true; 
     while((c=isr.read())!=-1) 
     { 
      chars++; 
      if(c=='\n') 
       lines++; 
      if(c=='\t' || c==' ' || c=='\n') 
       ++words; 
      if(chars!=0) 
       ++chars; 
     } 
     } 
    public static void main(String[] args) 
    { 
     FileReader fr; 
     try 
     { 
      if(args.length==0) 
      { 
       wc(new InputStreamReader(System.in)); 
      } 
      else 
      { 
       for(int i=0;i<args.length;i++) 
       { 
        fr=new FileReader(args[i]); 
        wc(fr); 
       } 
      } 

     } 
     catch(IOException ie) 
     { 
      return; 
     } 
     System.out.println(lines+" "+words+" "+chars); 
    } 
} 
+0

請嘗試格式化您的答案。要開始,對於代碼,使用4個空格縮進。有關更多信息,請訪問http://stackoverflow.com/help/formatting – 2016-11-27 04:07:09