纪念第一个有一丢丢作用的java程序,老师叫做的,虽然说不难,但是还是很有成就感,因为没学GUI,边看书边学边打的,所以很多地方不是很好,哈哈哈 ,记录一下,大佬们别嘲笑。。。。。。 代码如下:
package codecount01;
import java.io.*;
public class CodeCount {
//定义属性
static long emptyLines;//空行数
static long commentLines1;// //注释行数
static long commentLines2;// 注释行数
static long code;//代码行数
static long allline;//总行数
public static void quantity(File f) throws IOException {
if(f.isDirectory()==false){//判断:如果输入的不是目录,则直接进行数代码操作
if(f.getName().endsWith(".java")){//判断读取的是否时java文件
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String line=null;
line=br.readLine();
while (line!=null){//当此行不为空时
allline++;
line=line.trim();
if(line.length()==0){//字符串长度为零代表为空行
emptyLines++;
line=br.readLine();
}else if (line.startsWith("//")){// 以//开头代表为//注释行
commentLines1++;
line=br.readLine();
}else if(line.startsWith("")){//代表用"))){//当用")){//直到此行最后为*/结尾时跳出循环
commentLines2++;
line=br.readLine();
line=line.trim();
}
}else{
if (line.endsWith("*/")){//判断此行最后是否是*/,是则算为,不是则算为代码行
code++;
line = br.readLine();
}
}
}
br.close();
}
}else{//输入的文件是目录的话,进行下面操作
File[] Code=f.listFiles();//得到一个目录的数组
for (int i = 0; i
package codecount01;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import static javax.swing.JFileChooser.*;
public class TestGUI extends Jframe implements ActionListener {
JPanel jp=new JPanel();
//private JButton jb_open=new JButton("打开文件");
private JButton jb_choice=new JButton("选择文件");
private Jtextarea log=new Jtextarea(10,20);
private JFileChooser jfc=new JFileChooser();
public TestGUI(){
super("代码统计器");
init();
}
public void init(){
setSize(900,500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
//jb_open.setIcon(new ImageIcon(TestGUI.class.getResource()));
//jb_open.addActionListener(this);
//jb_choice.setIcon(new ImageIcon(TestGUI.class.getResource()));
jb_choice.addActionListener(this);
//jp.add(jb_open);
jp.add(jb_choice);
add(jp,BorderLayout.NORTH);
add(new JScrollPane(log),BorderLayout.CENTER);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(jb_choice)){
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);//可以选择文件夹和文件
int n=jfc.showOpenDialog(TestGUI.this);
if(n==0) {
File file = new File(jfc.getSelectedFile().getAbsolutePath());
CodeCount c=new CodeCount();//创建一个CodeCount对象用来调用下面的方法和数据
//File f=new File();
try {
c.quantity(file);
} catch (IOException ioException) {
ioException.printStackTrace();
}
//log.append("你打开了:" + file.getName() + "!n");
//清屏操作
log.setText("");
//输出
log.append("空行数:"+ c.emptyLines+"n");
log.append("代码数:"+c.code + "n");
log.append("//注释数:"+c.commentLines1 + "n");
log.append("
}
}



