JAVA第一次作业

要求: 给定一个源代码文件(.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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值