The issue with the code is in the recursive call to "countLines(file.getAbsolutePath())" inside the "if (file.isDirectory())" condition. \n\nThe "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. \n\nTo 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. \n\nHere's the updated code:\n\njava\npackage serializable.zuoye3;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\n\npublic class demo2 {\n public static void main(String[] args) {\n String directory = \"D:\\powernode\\weihc\\weihc19\\src\\serializable\\zuoye3\\demo1.java\"; // 指定目录路径\n int totalLines = countLines(directory);\n System.out.println(\"总行数:\" + totalLines);\n }\n\n public static int countLines(String directory) {\n File dir = new File(directory);\n if (!dir.isDirectory()) {\n System.out.println(\"指定路径不是一个目录!\");\n return 0;\n }\n\n int totalLines = 0;\n File[] files = dir.listFiles();\n for (File file : files) {\n if (file.isDirectory()) {\n totalLines += countLines(file.getAbsolutePath());\n } else if (file.getName().endsWith(\".java\")) {\n int lines = countFileLines(file);\n totalLines += lines;\n System.out.println(file.getName() + \":\" + lines + \"行\");\n }\n }\n\n return totalLines;\n }\n\n public static int countFileLines(File file) {\n int lines = 0;\n try (BufferedReader reader = new BufferedReader(new FileReader(file))) {\n String line;\n while ((line = reader.readLine()) != null) {\n if (!line.trim().isEmpty()) {\n lines++;\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return lines;\n }\n}\n\n\nThis should resolve the issue and correctly calculate the total number of lines in the specified directory and its subdirectories.

Java 代码错误修复:计算目录下所有 .java 文件的行数

原文地址: https://www.cveoy.top/t/topic/p9fi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录