javapackage serializablezuoye3;import javaioBufferedReader;import javaioFile;import javaioFileReader;import javaioIOException;public class demo2 public static void mainString args String d
The issue with the code is in the recursive call to countLines(file.getAbsolutePath()) inside the if (file.isDirectory()) condition.
The countLines method is declared to return void, but in the recursive call, you are trying to add its return value to totalLines. This is causing the error.
To fix this, you need to change the return type of the countLines method from void to int. Then, you can return the totalLines at the end of the method.
Here's the updated code:
package serializable.zuoye3;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class demo2 {
public static void main(String[] args) {
String directory = "D:\\powernode\\weihc\\weihc19\\src\\serializable\\zuoye3\\demo1.java"; // 指定目录路径
int totalLines = countLines(directory);
System.out.println("总行数:" + totalLines);
}
public static int countLines(String directory) {
File dir = new File(directory);
if (!dir.isDirectory()) {
System.out.println("指定路径不是一个目录!");
return 0;
}
int totalLines = 0;
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
totalLines += countLines(file.getAbsolutePath());
} else if (file.getName().endsWith(".java")) {
int lines = countFileLines(file);
totalLines += lines;
System.out.println(file.getName() + ":" + lines + "行");
}
}
return totalLines;
}
public static int countFileLines(File file) {
int lines = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
lines++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
}
This should resolve the issue and correctly calculate the total number of lines in the specified directory and its subdirectories
原文地址: https://www.cveoy.top/t/topic/irD9 著作权归作者所有。请勿转载和采集!