0

文字列の単語を二分木に挿入するために書いたメソッドに問題があります。以下のコードは問題のメソッドです。基本的に、単語がまだツリーにない場合 ( としてBinaryTreeNode) 挿入され、ツリーにある場合は、その頻度 ( 内のカウント変数BinaryTreeNode) が 1 つ増加します。私の問題は一時変数にありますsearchWord。として定義すると、タイプの不一致が生じ、 typeに対して is not definedStringというステートメントが作成されます。ジェネリック型はプレースホルダーとしてのみ存在し、これも機能しません。では、何と定義すればよいのでしょうか。getFrequency()StringT

buildBinaryTree メソッド:

public static void buildBinaryTree(String word) {
    //if word is already in tree
    if(wordTree.contains(word)) {
        //find existing word node
        T searchWord = wordTree.find(word);  //problem here

        //increment frequency by 1
        searchWord.setFrequency(searchWord.getFrequency() + 1);
    } else {
        //add word to tree
        System.out.println(word);
        wordTree.addElement(word);
    }
}

BinaryTreeNode コンストラクター:

/**
 * Creates a new tree node with the specified data.
 * @param obj the element that will become a part of the new tree node
 */
BinaryTreeNode(T obj) {
   element = obj;
   left = null;
   right = null;
   frequency = 1;
}

頻度の取得/設定メソッド:

/**
 * Gets the frequency.
 * @return the frequency
 */
public int getFrequency() {
   return frequency;
}

/**
 * Sets the frequency.
 * @param frequency the frequency to set
 */
public void setFrequency(int frequency) {
   this.frequency = frequency;
}
4

1 に答える 1

1

チャットで話した後、型変数 を置き換えるために、バイナリ ツリーに配置する型として使用するStringとの両方を持つクラスを定義する必要があります。次に、を返す、頻度に 1 を追加するなどのメソッドを定義できます。バイナリ ツリーからオブジェクトを取得すると、これらのメソッドを呼び出すのに適した型になります。intTgetString()StringincrementFrequency()

于 2012-04-10T03:31:00.883 に答える