利用Java簡單實現一個程式碼行數統計器方法例項
阿新 • • 發佈:2020-11-10
前言
哈嘍,我是小黑, 最近學了java的輸入輸出流後一直心癢癢,總想找一點事情來做,所以用java程式碼來實現了一下統計程式碼的所有行數,看一下我上大學以來到底打了多少行。
先附上實現程式碼吧!
package InOutStream; import java.util.* ; import java.io.* ; class codeCount { private static int count ; //統計總行數 private static int countCPP ;//CPP private static int countJAVA ;//java private static int countPY ;//python private String path ; //用於接收使用者輸入儲存程式碼的資料夾的路徑 private int reading(String path) throws Exception { //該函式用來統計一個程式碼檔案的行數 FileReader reader = new FileReader(path) ; BufferedReader buffer = new BufferedReader(reader) ; int count = 0 ; while(buffer.readLine()!=null) { count ++ ; } buffer.close() ; reader.close() ; return count ; } private void caculate(String nowpath) throws Exception{//計數函式 File nowfile = new File(nowpath) ; if (nowfile.isFile()) { if (nowpath.endsWith(".cpp")) { int sum = reading(nowpath) ; countCPP += sum ; count += sum ; } else if (nowpath.endsWith(".py")) { int sum = reading(nowpath) ; countPY += sum ; count += sum ; } else if (nowpath.endsWith(".java")) { int sum = reading(nowpath) ; countJAVA += sum ; count += sum ; } else { System.out.println(nowpath.substring(nowpath.indexOf("."))+":該型別檔案不屬於程式碼檔案或該程式碼檔案統計功能正在開發中,敬請期待!"); } } else { //如果這個路徑表示的是一個資料夾,則執行遞迴操作 String []filesset = nowfile.list() ; for (String i:filesset ) { String newpath = nowpath + nowfile.separator + i ;//合成路徑 caculate(newpath) ; } } } public codeCount(String src) { path = src ; } public static int getLinesCPP() { return countCPP ; } public static int getLinesJAVA() { return countJAVA ; } public static int getLinesPY() { return countPY ; } public static int getLines() { return count ; } public void caculator() throws Exception { //外界包裝 this.caculate(path) ; } public String toString() { //重寫toString方法 return "統計結果如下:\n" + "cpp行數:\n"+countCPP + "\njava行數:\n"+countJAVA + "\npython行數:\n"+countPY ; } } public class Count{ public static void main(String []args) throws Exception { Scanner cin = new Scanner(System.in) ; System.out.println("請輸入地址:"); String path = cin.next() ; codeCount machine = new codeCount(path) ; machine.caculator(); System.out.println(machine.toString()); cin.close(); } }
例項:
我在桌面儲存了一個資料夾用來儲存程式碼:
開啟後是這個樣子:
取路徑:
執行程式,將路徑貼上到程式之內
結果如下!!!
這就是所有程式碼拉!!如果你有其他什麼實現方法或者意見或者建議,歡迎在評論區中提出來哦!
ps:由於我只學了c、cpp、java、python。所以程式碼中只針對這幾種進行了統計,歡迎您修改程式碼來滿足您的需求!!
總結
到此這篇關於利用Java簡單實現一個程式碼行數統計器的文章就介紹到這了,更多相關Java實現程式碼行數統計器內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!