首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

有个小程序递归部分出了有关问题

2012-01-30 
有个小程序递归部分出了问题。Java codepackage countingprogramimport java.awt.BorderLayoutimport jav

有个小程序递归部分出了问题。

Java code
package countingprogram;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Frame;import java.awt.Label;import java.awt.Panel;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.*;import java.io.*;import java.util.ArrayList;public class CodeCounting {    public static void main(String[] args) {        new MyCountingFrame("程序代码统计小程序");    }}class MyCountingFrame extends Frame {    private static final long serialVersionUID = 1L;    static int sum = 0,realsum = 0,space = 0,note = 0;    static String b = " ";    TextArea ta1 ;    TextField t1;    Label l1 ;        MyCountingFrame(String s){        super(s);        setBounds(300,300,400,400);        addWindowListener(new WindowAdapter(){            public void windowClosing(WindowEvent e)  {                setVisible(false);                System.exit(0);            }        });        Panel p1 = new Panel();        l1 = new Label("请输入你要查询的路径");        t1 = new TextField(20);        Button b1 = new Button("确定");        b1.addActionListener(new MyListener());        p1.add(t1);        p1.add(l1);        p1.add(b1);        ta1 = new TextArea(20,10);        add(p1,BorderLayout.SOUTH );        add(ta1,BorderLayout.CENTER );        setVisible(true);    }        class MyListener implements ActionListener {        public void actionPerformed(ActionEvent e){            ta1.setText(" ");            String pathname = t1.getText();                        if(b.equals(pathname)){                ta1.append("输入重复");            }else if(pathname.matches("^.+:\\\\+.*")){                l1.setText("计算中");                new Counting (pathname);                l1.setText("计算完成");                 b = t1.getText();                 t1.setText(" ");            }else if(pathname.matches("^.+:\\\\.+\\\\$")){                l1.setText("计算中");                new Counting (pathname);                l1.setText("计算完成");                b = t1.getText();                t1.setText(" ");                }else{                ta1.setText("输入错误");                ta1.append("/ 或者\\ 的符号请用 ' \\\\ '来代替");            }        }    }        class Counting {        String pathname;                ArrayList<File> fileall = new ArrayList<File>();        Counting(String pathname){//构造函数,运行主程序            this.pathname = pathname;            launch();            sum = 0;            realsum = 0;            space = 0;            note = 0;        }                public void launch(){//检查后缀名并运行搜索程序。        File  file = new File(pathname);        /*File [] file1 = file.listFiles();        for(File c:file1){            fileall.add(c);        }*/         myFileList(file);//递归调用                 for(File child:fileall){            if(child.getName().matches(".*\\.java$")){                check(child);            }        ta1.setText("sum:" + sum + " \n" + "note:" + note + "\n" +  "space:" + space + "\n" +  "realsum:" + realsum);            }        }                public void  myFileList(File f){            File[] file2 = f.listFiles();                        for(File kid : file2){                if(kid.isDirectory()){                    myFileList(kid);                }                fileall.add(kid);            }        }                private void check( File child2 ) {//search program is starting...            BufferedReader br = null;            String line;            boolean comment = false;                        try{            br = new BufferedReader(new FileReader(child2));            while((line =  br.readLine()) != null){            sum++;            line = line.trim();            if(line.matches("[\\s&&[^\\n]]*$")){                space++;            }else if(line.startsWith("/*")&& !line.endsWith("*/")){                note++;                comment = true;            }else if(true == comment){                note++;                if(line.endsWith("*/")){                    comment = false;                }            }else{                realsum++;                }            }            }catch (FileNotFoundException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }finally {                if(br != null) {                    try {                        br.close();                        br = null;                    } catch (IOException e) {                        e.printStackTrace();                }            }              }        }      }    } 



使用被注释的部分可以运行,使用myFileList这个递归方法出现
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at countingprogram.MyCountingFrame$Counting.myFileList(CodeCounting.java:114)
at countingprogram.MyCountingFrame$Counting.myFileList(CodeCounting.java:116)
at countingprogram.MyCountingFrame$Counting.launch(CodeCounting.java:101)
at countingprogram.MyCountingFrame$Counting.<init>(CodeCounting.java:88)
at countingprogram.MyCountingFrame$MyListener.actionPerformed(CodeCounting.java:65)
at java.awt.Button.processActionEvent(Button.java:392)
小程序用于统计java代码。望各位指点。

[解决办法]
Java code
package codeCount;import java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.*;public class Test {    public static void main(String[] args) {    new PrimaryFrame();    }}class PrimaryFrame extends JFrame {    PrimaryPanel PrimaryPanel;// Frame上只有Panel 和JTextArea    JTextArea jTextArea;    public PrimaryFrame() {    init();    }    private void init() {    setTitle("PrimaryFrame");    setLayout(new BorderLayout());    jTextArea = new JTextArea();    add(jTextArea, BorderLayout.CENTER);    PrimaryPanel = new PrimaryPanel(this);// -----------------面板JPanel    add(PrimaryPanel, BorderLayout.SOUTH);    setPreferredSize(new Dimension(400, 400));    pack();    setVisible(true);    setResizable(false);    setLocationRelativeTo(null);    setDefaultCloseOperation(EXIT_ON_CLOSE);    }    public void displayInfo(long sumLines, long normalLines, long commentLines,        long whiteLines) {// Frame的功能 只显示结果    StringBuffer stringBuffer = new StringBuffer();    stringBuffer.append("sumLine = " + sumLines);    stringBuffer.append("\nnormalLine = " + normalLines);    stringBuffer.append("\ncommentLine = " + commentLines);    stringBuffer.append("\nwhiteLine = " + whiteLines);    jTextArea.setText(stringBuffer.toString());    }}// //////////////////////////////////////////////////////////////////////////////////////////////class PrimaryPanel extends JPanel {    PrimaryFrame primaryFrame;    JButton openDirectoryButton;// panel上有两只按钮,为了打开文件和目录    JButton openFileButton;    public PrimaryPanel(PrimaryFrame primaryFrame) {    this.primaryFrame = primaryFrame;    init();    }    private void init() {    openDirectoryButton = new JButton("打开目录");// 添加统计文件夹中java文件的信息的按钮    openFileButton = new JButton("打开文件");// 添加统计单个java文件的信息的按钮    openDirectoryButton        .addActionListener(new OpenDirectoryButtonActionListener(this));    add(openDirectoryButton);    openFileButton        .addActionListener(new OpenFileButtonActionListener(this));    add(openFileButton);    }    public void execute(boolean b) {// 面板仅有的功能,将获取的信息传递给Frame    CodeCounter codeCounte = new CodeCounter(b);    // check pathName    primaryFrame.displayInfo(codeCounte.getSumLines(), codeCounte        .getNormalLines(), codeCounte.getCommentLines(), codeCounte        .getWhiteLines());    }}// /////////////////////////////////////////////////////////////////////////////////////////////class OpenDirectoryButtonActionListener implements ActionListener {// 打开目录监听器    PrimaryPanel primaryPanel;    public OpenDirectoryButtonActionListener(PrimaryPanel primaryPanel) {    this.primaryPanel = primaryPanel;    }    public void actionPerformed(ActionEvent e) {    primaryPanel.execute(true);// 如果是文件夹    }}// /////////////////////////////////////////////////////////////////////////////////////////////class OpenFileButtonActionListener implements ActionListener {// 打开文件监听器    PrimaryPanel primaryPanel;    public OpenFileButtonActionListener(PrimaryPanel primaryPanel) {    this.primaryPanel = primaryPanel;    }    public void actionPerformed(ActionEvent e) {    primaryPanel.execute(false);// 如果是文件    }}// /////////////////////////////////////////////////////////////////////////////////////////////class CodeCounter {// 代码统计器,返回四个参数    private long sumLines = 0;// 总行数    private long normalLines = 0;// 代码行    private long commentLines = 0;// 注释行    private long whiteLines = 0;// 空白行    public CodeCounter(String pathName) {// 根据不同构造函数和参数执行不同的操作    getInfo(new File(pathName));    }    public CodeCounter(boolean b) {//    if (b)        getInfo(getDirectoryName());    else        getInfo(getFileName());    }    public void getInfo(File f) {// 对文件夹及其子文件夹中的所有java代码进行统计    if (f == null || !f.exists())        return;    if (f.isFile())        parse(f);    // System.out.println(f.getName());    else {        File[] files = f.listFiles();        if (files != null)        for (File file : files)            getInfo(file);    }    }    private void parse(File f) {// 对单个java文件进行统计    if (f == null || !f.exists() || !f.getName().matches(".*.java$")) {        return;    }    BufferedReader br = null;    boolean comment = false;    try {        br = new BufferedReader(new FileReader(f));        String line = "";        while ((line = br.readLine()) != null) {        line = line.trim();        if (line.matches("^[\\s&&[^\\n]]*$")) {            whiteLines++;        } else if (line.startsWith("/*") && !line.endsWith("*/")) {            commentLines++;            comment = true;        } else if (line.startsWith("/*") && line.endsWith("*/")) {            commentLines++;        } else if (true == comment) {            commentLines++;            if (line.endsWith("*/")) {            comment = false;            }        } else if (line.startsWith("//")) {            commentLines++;        } else {            normalLines++;        }        }        sumLines = normalLines + commentLines + whiteLines;    } catch (FileNotFoundException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    } finally {        if (br != null) {        try {            br.close();            br = null;        } catch (IOException e) {            e.printStackTrace();        }        }    }    }    public long getNormalLines() {    return normalLines;    }    public long getCommentLines() {    return commentLines;    }    public long getWhiteLines() {    return whiteLines;    }    public long getSumLines() {    return sumLines;    }    public File getFileName() {// 如果第二个构造方法的参数是false,则执行获取文件名的功能    JFileChooser jFileChooser = new JFileChooser();    int returnValue = jFileChooser.showOpenDialog(null);    if (returnValue == JFileChooser.APPROVE_OPTION) {        File file = jFileChooser.getSelectedFile();        return file;    }    return null;    }    public File getDirectoryName() {// 如果第二个构造方法的参数是false,则执行获取目录名的功能    JFileChooser jFileChooser = new JFileChooser();    jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);    // DIRECTORIES_ONLY就是只选目录    int returnValue = jFileChooser.showOpenDialog(null);    if (returnValue == JFileChooser.APPROVE_OPTION) {        File file = jFileChooser.getSelectedFile();        return file;    }    return null;    }}// /////////////////////////////////////////////////////////////////////////////////////////////////////// 

热点排行