Во-первых, следующий код запускает текстовый файл с 37.000 символов (работает нормально). Я хочу рассчитать возможность появления каждого персонажа. Итак, для достижения этой цели мне нужно посчитать, сколько раз каждая буква появляется в файле test.txt.
File file = new File("test.txt");
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
String line;
// Initializing counters
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int whitespaceCount = 0;
int a,b,c,d,e,f,g,h,i,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z=0;
// Reading line by line from the
// file until a null is returned
while((line = reader.readLine()) != null) {
if(!(line.equals(""))) {
characterCount += line.length();
// \\s+ is the space delimiter in java
String[] wordList = line.split("\\s+");
countWord += wordList.length;
whitespaceCount += countWord -1;
// [!?.:]+ is the sentence delimiter in java
String[] sentenceList = line.split("[!?.:]+");
sentenceCount += sentenceList.length;
}
}
System.out.println("Total number of characters = " + characterCount);
System.out.println("Total number of whitespaces = " + whitespaceCount);
}
Я думаю о следующем коде, но я уверен, что это что-то более эффективный с более коротким кодом.
while((line = reader.readLine()) != null)
if(!(line.equals(""))) {
characterCount += line.length();
if (line.equals("a")){
a++;
}...
//same for the rest letters.