このクラスの最後の for ループが原因です。新しく作成された配列にモードワードを書き込みます。for ループは、Eclipse デバッガーが値 i を (tokens.length-2) より小さいと表示しても、最終的に反復しません。おそらくフェンスポストの問題かもしれませんが、do while ループなどを試してみました。さらに、使用しているクライアント コードと txt ファイルを投稿しました。
// This class creates an object wherein a text file is segmented and stored
// word for word in an array, facilitating a word count, the ability to check
// for the occurrence of a word and also the functionality of returning the
// most frequently occurring words.
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class TextAnalysis14 {
private String[] tokens;
int maxNoOfWords;
// Constructor that loads a file and assigns each word to an array index
public TextAnalysis14 (String sourceFileName, int maxNoOfWords) throws FileNotFoundException{
this.maxNoOfWords = maxNoOfWords;
Scanner in = new Scanner(new FileReader(sourceFileName));
String file = in.useDelimiter("\\Z").next();
this.tokens = file.split ("[^a-zA-Z]+");
in.close();
}
// Returns the number of words in the file.
public int wordCount(){
return tokens.length;
}
// Checks whether " word " is a word in the text.
public boolean contains(String word){
for(int i=0; i<tokens.length; i++){
if(tokens[i].equalsIgnoreCase(word)){return true;}
}
return false;
}
// Returns the most frequent word(s) in lexicographical order.
public String [] mostFrequentWords(){
Arrays.sort(tokens);
//Finds the mode word occurrence
int wordValue=1;
int maxValue=1;
for(int i=0; i<tokens.length-2; i++){
while(tokens[i].equalsIgnoreCase(tokens[i+1])){
wordValue++;
i++;
}
if(wordValue>maxValue){
maxValue=wordValue;
}
wordValue=1;
}
//Determines length of return array
int numberOfModes=1;
for(int i=0; i<tokens.length-2; i++){
while(tokens[i].equalsIgnoreCase(tokens[i+1])){
wordValue++;
i++;
}
if(wordValue==maxValue){
numberOfModes++;
}
wordValue=1;
}
//writes mode words to array
int cursor =0;
String[] modeWords = new String[numberOfModes];
for(int i=0; i<tokens.length-2; i++){
while(tokens[i].equalsIgnoreCase(tokens[i+1])){
wordValue++;
i++;
}
if(wordValue==maxValue){
modeWords[cursor]=tokens[i];
cursor++;
}
wordValue=1;
}
return modeWords;
}
}
以下は私のクライアントコードです:
import java.io.FileNotFoundException;
import java.util.Arrays;
public class TextAnalysis_test01 {
public static void main(String[] args) throws FileNotFoundException {
TextAnalysis14 ta14 = new TextAnalysis14("testtext01.txt", 100);
System.out.println(ta14.wordCount());
System.out.println(ta14.contains("Bla"));
System.out.println(ta14.contains("hello"));
System.out.println(Arrays.toString(ta14.mostFrequentWords()));
}
}
以下は私のtxtファイルの内容です:
bla bla
dim dim
dum dum
そして、私は出力を取得します:
6
true
false
[bla, dim, null]
明らかなように、返された文字列配列の最後のインデックスには何も書き込んでいません。これは、最後の for ループが最後に繰り返されていないためです。私のクラスの一部は次のようにコメントされています: //writes mode words to array.
助けやアドバイスは天の恵みです。乾杯!