<pre name="code" class="java">package test1;
import 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 StaticsCodeingLine {
private static int whiteLines = 0; //定义空白行数
private static int commentLines = 0; //定义注释行数
private static int normalLines = 0; //定义有效代码行数
/**
* @param args
*/
public static void main(String[] args)throws IOException {
//File f = new File("F:\\workspace\\qiang\\src\\qiang\\StaticsCodeingLine.java"); //创建一个文件,并且输入要统计的文件名路径
//sumCode(f); //统计f中代码数
System.out.println("请输入你想要计算文件的名称:");
Scanner in = new Scanner(System.in);
String str =in.nextLine();
try{
@SuppressWarnings("unused")
String encoding="";
File f =new File("F:\\workspace\\qiang\\src\\qiang\\"+str);
sumCode(f);
}catch(Exception e){
System.out.println(e);
}
}
private static void sumCode(File file) {
BufferedReader br = null;
boolean comment = false;
try { //开始捕获异常
br = new BufferedReader(new FileReader(file));
String line = ""; //字符串类对象
try {
while ((line = br.readLine()) != null) {
line = line.trim(); //注:去除每行行首和行尾的空格 但不会删除换行符 区分开空白行与前面有缩进的代码行
if (line.matches("^[\\s&&[^\\n]]*$")) //空白行:以空白字符“ \t\n\x0B\f\r”开始且不含换行符
//java中\n表示换行,\s匹配任意的空白符 包括换行符
{
whiteLines++;
} else if (line.startsWith("/*") && !line.endsWith("*/")) //判断以"/*" 和" */"开头的的注释行
{
commentLines++;
comment = true;
} else if (true == comment) {
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) {
int TotalLines = whiteLines+commentLines+normalLines;
try {
System.out.println("空行数:"+whiteLines);
System.out.println("注释行数:"+commentLines);
System.out.println("代码行数:"+normalLines);
System.out.println("总行数:"+TotalLines);
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Java第一次作业:源代码计算器 第二问
最新推荐文章于 2021-03-08 07:29:16 发布