2017-09-23 56 views
-3

我需要操作此代碼,以便它將讀取文件中的位數。 由於某種原因,我被老實說服了。我需要先標記它嗎? 謝謝!操作此代碼,以便它計算文件中的位數#

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

public class CountLetters { 

    public static void main(String args[]) { 
     if (args.length != 1) { 
      System.err.println("Synopsis: Java CountLetters inputFileName"); 
      System.exit(1); 
     } 
     String line = null; 
     int numCount = 0; 
     try { 
      FileReader f = new FileReader(args[0]); 
      BufferedReader in = new BufferedReader(f); 
      while ((line = in.readLine()) != null) { 
       for (int k = 0; k < line.length(); ++k) 
        if (line.charAt(k) >= 0 && line.charAt(k) <= 9) 
         ++numCount; 
      } 
      in.close(); 
      f.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     System.out.println(numCount + " numbers in this file."); 
    } // main 
} // CountNumbers 
+2

如果您要求人們嘗試閱讀,您應該[確保您的代碼正確縮進](https://stackoverflow.com/posts/46385103/edit)。 – khelwood

+0

歡迎來到Stack Overflow。你已經嘗試過這麼做了什麼?請回顧[我如何問一個好問題](https://stackoverflow.com/help/how-to-ask)。堆棧溢出不是一種編碼服務。預計您會在發佈之前研究您的問題,並嘗試親自編寫代碼***。如果您遇到* specific *,請返回幷包含[Minimal,Complete和Verifiable示例](https://stackoverflow.com/help/mcve)以及您嘗試的內容摘要,以便我們提供幫助。 – FluffyKitten

+0

你的輸入文件是什麼? – tommybee

回答

2

使用''指示char常數(你是比較char s到int S),我也建議你使用try-with-resources Statement避免明確收市話費和請避免使用一個線環沒有括號(除非你是使用lambda)。像

public static void main(String args[]) { 
    if (args.length != 1) { 
     System.err.println("Synopsis: Java CountLetters inputFileName"); 
     System.exit(1); 
    } 
    String line = null; 
    int numCount = 0; 
    try (BufferedReader in = new BufferedReader(new FileReader(args[0]))) { 
     while ((line = in.readLine()) != null) { 
      for (int k = 0; k < line.length(); ++k) { 
       if ((line.charAt(k) >= '0' && line.charAt(k) <= '9')) { 
        ++numCount; 
       } 
      } 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    System.out.println(numCount + " numbers in this file."); 
} // main 

此外,您還可以使用正則表達式刪除所有非數字(\\D),並添加所產生的String的長度(這是所有位)。像,

while ((line = in.readLine()) != null) { 
    numCount += line.replaceAll("\\D", "").length(); 
} 
1

使用if(Charachter.isDigit(char))每個字符替換字符,這將統計每個號碼,我相信阿拉伯數字爲好。

相關問題