2017-09-23 57 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))每个字符替换字符,这将统计每个号码,我相信阿拉伯数字为好。

相关问题