Cześć,
Robie sobie taki programik, ktory ze Stringa "code" policzy ile jest prymitywów oraz ile jest Stringów.
Prawidłowy wynik w tym przypadku to:
String -> 2
int -> 1
double -> 1
public static void main(String[] args) {
String code = " String marek = \"Marek\";\n" +
" int integer=0;\n" +
"\n" +
" // int xy = 9;\n" +
" // to jest komentarz int xy = 9\n" +
" /* cześc jak się masz */\n" +
" double pensja = 312.00;\n" +
" /*\n" +
" int x = 5;\n" +
" int y = 6;\n" +
" */\n" +
" String napis = \"int o = 0;\\n\" + \"double xo = 12; String xlz = \\\"halo\\\";\";";
int stringCount = countOccurrences(code, "String");
int intCount = countOccurrences(code, "int");
int doubleCount = countOccurrences(code, "double");
System.out.println("String -> " + stringCount);
System.out.println("int -> " + intCount);
System.out.println("double -> " + doubleCount);
}
private static int countOccurrences(String code, String word) {
code = code.replaceAll("\"(\\\\.|[^\"\\\\])*\"", "");// tu są literały stringowe
code = code.replaceAll("//.*", ""); // tu są komentarze jednoliniowe
code = code.replaceAll("/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/", ""); // tu są komentarze blokowe
Matcher matcher = Pattern.compile("\\b" + word + "\\b").matcher(code);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
Chciałbym teraz trochę ten program urozmaicić i zrobić, aby zaczytywał on z pliku xyz.java
, a nie ze Stringa code.
W momencie gdy używam BufferedReader
a to daje niewłaściwy odczyt.
Stworzyłem taką metodę:
private static String readCodeFromFile(String filePath) {
StringBuilder code = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
code.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return code.toString();
}
I teraz po odpaleniu wynik jest:
String -> 3
int -> 1
double -> 1
W czym leży problem?