私はクラス辞書を持っています。いくつかの単語を含むテキスト ファイルを (メイン メソッドから) 読み取り、それらをハッシュ セットに格納するだけです。このクラスには、ハッシュセットに特定の単語が含まれているかどうかをチェックし、ブール値を返すメソッド「contains」(static) もあります。ハッシュセット変数も静的として定義されています。
さて、別のプログラムがあり、静的メソッド「contains」を呼び出した場合、Dictionary クラスの「main」メソッドは実行されますか? 私のプログラムでは、Dictionary が空であるため実行されないようです (contains メソッドへの呼び出しはすべて false を返します)。main メソッドを確実に実行して辞書を埋めるにはどうすればよいですか?
もちろん、メソッドを非静的にして辞書オブジェクトを作成するか、呼び出しプログラムの内部クラスとして辞書を作成することができます。しかし、これを行うためのより良い方法があるかどうかを知りたいだけです。
必要に応じてコードを共有します。
PS: Dictionary クラスは独立して実行すると問題なく動作し、「contains」メソッドの呼び出しも問題なく動作します。
private static Set<String> dictionary = new HashSet<String>();
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
System.out.println("Reading dictionary....");
FileReader fr = new FileReader("dictionary.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null){
dictionary.add(s);
}
br.close();
fr.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
System.out.println("Dictionary contains the following words");
for(String s : dictionary){
System.out.println(s);
}
}
public static boolean contains(String inpword){
//String[] args = new String[0];
//main(args);
if(dictionary.contains(inpword))
return true;
return false;
}