哈嘍,我是小黑, 最近學了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,所以代碼中只針對這幾種進行了統計,歡迎您修改代碼來滿足您的需求!!
接下來我會學習swing,到時候會嘗試著把這個代碼生成圖形化界面,歡迎持續關注我拉!!!
謝謝閱讀!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/208908.html
標籤:其他
下一篇:假設認識Java的第二天
