C#源代码统计程序

来源:互联网 发布:淘宝动态评分提高 编辑:程序博客网 时间:2024/05/21 20:21

题目:给定一个源代码文件(.cs, .java),输出该文件的总行数、空行数、注释行数、代码行数。

【1】定义一个文件操作接口(FileInterface.java):

import java.io.File;interface FileInterface {public void computing(File file) ;}

【2】定义一个实现文件接口的Computer类(Computing.java:):

import java.io.File; import java.io.BufferedReader; import java.io.FileReader;  import java.io.FileNotFoundException;  import java.io.IOException;  //定义一个实现文件接口的Computer类public class Computing implements FileInterface{    //声明代码行数变量    private static int daima = 0 ;      //声明空白行数变量        private static int nothing = 0;      //声明注释行数变量    private static int explain= 0;        //定义computing方法,对文件进行操作,读取文件计算文件空白行数、注释行数、代码行数   public  void computing(File file) {       BufferedReader buf = null;          boolean comment = false;   //定义一个boolean标记对象,对注释行进一步判断       try {              buf = new BufferedReader(new FileReader(file));  //创建一个字符输入处理流对象对文件进行操作           try {                  comment = judging(buf,comment);   //调用判断文件的方法           } catch (IOException e) {                      e.printStackTrace();                }       }catch (FileNotFoundException e) {                  e.printStackTrace();        }finally {         if (buf != null) {             printResult(buf);   //调用统计输出结果的方法          }        }      }   //文件判断方法   private boolean judging(BufferedReader buf, boolean comment) throws IOException {                        String line = "";   while ((line = buf.readLine()) != null) {   //读取一行   line = line.trim();   //去掉左右空格及空字符   if (line.matches("")) {   //判断是否为空格或者空字符,是的话空白行数加1    nothing++;      } else if (line.startsWith("/*") && !line.endsWith("*/")) {   //判断是否为注释行,是的话注释行数加1    explain++;          comment = true;      } else if (true == comment) {       explain++;          if (line.endsWith("*/")) {              comment = false;          }      } else if (line.startsWith("//")) {       explain++;      } else {   //以上判断都不是的话就为代码行数加1    daima++;      }   }return comment;}//统计结果输出方法private void printResult(BufferedReader buf) {try {   //输出空行数      System.out.println("空行数:"+nothing);   //输出注释行数      System.out.println("注释行数:"+explain);    //输出代码行数      System.out.println("代码行数:"+daima);  //输出文件总行数      System.out.println("文件总行数:"+(nothing+explain+daima));      buf.close();   //关闭BufferedRead流      buf = null;           } catch (IOException e){              e.printStackTrace();          }}}
【3】定义主函数,调用Computer类相关方法(Main_Java .java:):

import java.io.File;//定义主函数,调用Computer类相关方法public class Main_Java {     public static void main(String[] args) {     File f = new File("E:" + File.separator + "javaComputing.java");          Computing com = new Computing() ;        com.computing(f) ;    }}

【4】程序运行结果:







0 0
原创粉丝点击