JAVA第一次作业

来源:互联网 发布:java程序性能优化 豆瓣 编辑:程序博客网 时间:2024/06/10 09:17

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

mport java.io.BufferedReader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class nm {
 private static int whiteLines = 0;
 private static int commentLines = 0;
 private static int normalLines = 0;
 int totleLines;

public static void main(String[] args) throws FileNotFoundException {
 System.out.println("请输入文件名:(temp.txt)");
    Scanner sc = new Scanner(System.in);
  String filename = sc.next();
  BufferedReader br = null;
   boolean comment = false;
   try {
   br = new BufferedReader(new FileReader(filename));
   String line = "";
   try {
    while ((line = br.readLine()) != null)// line被赋值,并判断不等于null。赋值与判断为一体
     {
     line = line.trim(); //去除一行前后空格的行数
     if (line.matches("^[\\s&&[^\\n]]*$")) //正则表达式,这个正则表达式分两部分,先去掉头尾^和$两部分就是 [\\s&&[^\\n]]*和\\n前一部分可以不用管,主要在后一部分这后一部分就是匹配回车符的。由于java正则表达式字符串里\要转义,所以\要表示为 \\所以"\\n"实际上就是你需要的回车符。同时由于\\n$这个$的出现,前面的字符串必须是以\n结尾
     {
      whiteLines++;
     } else if (line.startsWith("/*") && !line.endsWith("*/")) // /*开头的注释行
     {
      commentLines++;
      comment = true;
     } else if (true == comment) //java中==是比较两者,正则表达式?
     {
      commentLines++;
      if (line.endsWith("*/")) {
       comment = false;
      }
     } else if (line.startsWith("//")) {
      commentLines++;
     } else {
      normalLines++;
     }
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  finally {
   if (br != null) {
    try {
     int totleLines= normalLines+commentLines+whiteLines;
     System.out.println("空行数:"+whiteLines);
     System.out.println("注释行数:"+commentLines);
     System.out.println("代码行数:"+normalLines);
     System.out.println("总行数:"+totleLines);
     br.close();
     br = null;
    }
    catch (IOException e)
    { e.printStackTrace();  }
   }
  }
 }

}

 


0 0
原创粉丝点击