《Java程序设计》第一次作业:源代码计算器

JAVA第一次作业(给定一个源代码文件,输出该文件的总行数、空行数、注释行数、代码行数...


<p><span style="color:#444444;">给定一个源代码文件(.cs, .java</span>),输出该文件的总行数、空行数、注释行数、代码行数。</p>
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * 
 * @author Administrator
 *
 */
public class JavaLine {
    private static final String PROJECT_DIR = "C:\\test";
    private static int totle = 0;       //总行数               
    private static int source  = 0;     //代码行数          
    private static int blank  = 0;      //空白行数              
    private static int comments = 0;    //注释行数
     
    /**
     * 读取文件夹内java文件
     * @param dir
     */
    private static void listNext(File dir) {
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            //判断是否是文件夹,如果是文件夹继续向下检索
            if (files[i].isDirectory()) {
                listNext(files[i]);
            } else {
                try {
                    if (files[i].getName().endsWith(".java")) {
                        System.out.println(files[i].getAbsolutePath());
                        javaLine(files[i]);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**
     * 读取java文件总行数,代码行数,空白行数,注释行数
     * @param f
     * @throws IOException 
     * @throws FileNotFoundException 
     */
    private static void javaLine(File f) throws FileNotFoundException, IOException{
        String strLine = "";
        String str = fromFile(f);
        if (str.length() > 0) {
            while (str.indexOf('\n') != -1) {
                totle++;
                //System.out.println(totle);
                strLine = str.substring(0, str.indexOf('\n')).trim();
                //str = str.substring(str.indexOf('\n') + 1, str.length());
                if (strLine.length() == 0 ) {
                    blank++;
                }else if (strLine.charAt(0) == '*' || strLine.charAt(0) == '/') {
                    comments++;
                }else{
                    source++;
                    String regEx = "^*//";
                    if(regEx(strLine,regEx)){
                        comments++;
                    }
                }
                str = str.substring(str.indexOf('\n') + 1, str.length());
            }
        }   
    }
     
    /**
     * 将java文件以字符数组形式读取
     * @param f
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static String  fromFile(File f) throws FileNotFoundException,IOException {
        FileInputStream fis = new FileInputStream(f);
        byte[] b = new byte[(int) f.length()];
        fis.read(b);
        fis.close();
        return new String(b);
    }
     
    /**
     * 正则匹配
     * @param str 输入字符串
     * @param regEx 正则匹配字符串
     * @return
     */
    private static boolean regEx(String str,String regEx){
        Pattern p=Pattern.compile(regEx);
        Matcher m=p.matcher(str);
        boolean result=m.find();
        return result;
    }
    public static void main(String[] args) throws FileNotFoundException, IOException {
        //File root = new File(PROJECT_DIR);
        File directory = new File("");//参数为空 
        //获取项目路径
        String projectFile = directory.getCanonicalPath() ;
        System.out.println(projectFile+"===============");
        listNext(new File(projectFile));
        System.out.println(totle+1);
        System.out.println(source);
        System.out.println(blank);
        System.out.println(comments);
    }
 
 
}

(尽量在4月5日之前完善作业。)

呃,正在思考,是否能从键盘上输入文件名,然后让不懂代码的人也能够查看文件的总行数、空行数、注释行数、代码行数。

更加希望有热心人给予相关的指导,谢谢。


老师给出的参考代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class ComputeSourceLine {

	public static void main(String[] args) throws FileNotFoundException {
		// TODO Auto-generated method stub
		
		// 定义相关变量
		int totalLine = 0;
		int emptyLine = 0;
		int commentLine = 0;
		int codeLine = 0;
		// 大家重点了解 Scanner类(网络搜索) 与 String类(教材P75及网络) 的使用
		// 文件的路径 
		String strFileName;
		// 使用命令行的方式,如果有命令行参数,则文件名从外界获取,否则使用指定文件
		// 使用方式: java ComputeSourceLine filename   (实际中用完整的文件名替代filename)
		if(args.length>=1)
			strFileName = args[0];
		else
			strFileName = "src/ComputeSourceLine.java";
		
		// 使用Scanner进行读文件 
		Scanner sc = new Scanner(new File(strFileName));
		while (sc.hasNextLine()) {
			String strTmp = sc.nextLine();
			// 去掉前后的空格
			strTmp = strTmp.trim();
			// 判断是否为空行、注释、代码行
			if(strTmp.length()==0)
				emptyLine ++;
			else if(strTmp.length()>2 && "//".equals(strTmp.substring(0,2))==true)
				commentLine ++;
			else
				codeLine ++;
			// System.out.println(strTmp);	          
		}
		// 关闭
		sc.close();
		totalLine = emptyLine+commentLine+codeLine;
		
		System.out.println("总行数="+totalLine);
		System.out.println("空行数="+emptyLine);
		System.out.println("注释行数="+commentLine);
		System.out.println("代码行数="+codeLine);
		
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java作业 科学计算器 menu切换普通与科学计算器 部分代码: class MyKey extends KeyAdapter { public void keyPressed(KeyEvent e) { char c = e.getKeyChar(); System.out.print(c); boolean bFlag = false; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if(IfResult){ tf.setText(""); IfResult = false; } tf.setText(tf.getText().trim() + c); bFlag = true; break; case '.': if(tf.getText().trim().indexOf(".") == -1){ tf.setText(tf.getText() + "."); } bFlag = true; break; case '_': if(Double.parseDouble(tf.getText()) > 0){ if(tf.getText().length() > 1){ tf.setText(tf.getText().substring(0, tf.getText().length() - 1)); }else{ tf.setText("0"); IfResult = true; } }else{ if(tf.getText().length() > 2){ tf.setText(tf.getText().substring(0, tf.getText().length() - 1)); }else{ tf.setText("0"); IfResult = true; } } bFlag = true; break; case '+': if(flag){ IfResult = false; } if(IfResult){ oper = "+"; }else{ getResult(Double.parseDouble(tf.getText())); oper = "+"; IfResult = true; } bFlag = true; break; case '-': if(flag){ IfResult = false; } if(IfResult){ oper = "-"; }else{ getResult(Double.parseDouble(tf.getText())); oper = "-"; IfResult = true; } bFlag = true; break; case '*': if(flag){ IfResult = false; } if(IfResult){ oper = "*"; }else{ getResult(Double.parseDouble(tf.getText())); oper = "*"; IfResult = true; } bFlag = true; break; case '/': if(flag){ IfResult = false; } if(IfResult){ oper = "/"; }else{ getResult(Double.parseDouble(tf.getText())); oper = "/"; IfResult = true; } bFlag = true; break; case '=': if(flag){ IfResult = false; } if(IfResult){ oper = "="; }else{ getResult(Double.parseDouble(tf.getText())); oper = "="; IfResult = true; } bFlag = true; break; } if(bFlag && tf.getText().equals("0")){ tf.setText("0"); IfResult = true; flag = true; } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值