2012-02-26 21 views
0

私は初心者のコーダーです。コンパイラーエラーが発生し続けるため、非常に不満を感じていました。これは宿題です。私がやるべきことは、Comparableクラスを実装して2つのStringオブジェクトを比較し、最大値と最小値を返すことです。私はコンパイラのエラーを取得し続け、私は正確になぜ私が知っていない。文字列を同等のインターフェイスに実装しています

public class DataSet implements Comparable 
{ 
    private Object maximum; 
    private Object least; 
    private int answer; 

public int compareTo(Object other) 
{ 
answer = this.getName().compareTo(other.getName()); 
return answer; 

} 

public Object getLeast(Object other) 
{ 
    if(answer<0) 
    return this; 
    else 
    return other; 
    } 

public Object getMaximum(Object other) 
{ 
    if(answer>0) 
    return this; 
    else 
    return other; 
} 


} 

エラーは、それらがオブジェクトを受け取るようメソッドが宣言されているのgetNameメソッド

public interface Comparable 
{ 
    public int compareTo(Object anObject); 
} 


public class DataSetTester 
{ 
public static void main(String[] args) 
{ 
    DataSet ds = new DataSet(); 
    String s = "john"; 
    String a = "bob"; 
    ds.s.compareTo(a); 
    System.out.println("Maximum Word: " + ds.getMaximum()); 
    System.out.println("Least Word: " + ds.getLeast()); 

} 
} 


incompatible types 
    String s = "john"; 

incompatible types 
    String a = "bob"; 

error: cannot find symbol 
    ds.s.compareTo(a); 

error: method getMaximum in class DataSet cannot be applied to given types; 
    System.out.println("Maximum Word: " + ds.getMaximum()); 
error: method getLeast in class DataSet cannot be applied to given types; 
    System.out.println("Least Word: " + ds.getLeast()); 
+0

私はあなたが割り当てを誤解していると考えてい呼び出す場合はint型を生成します。 Comparableは 'compareTo()'メソッドを含むインタフェースで、 'this'オブジェクトが他のオブジェクトよりも「より小さい」、「等しい」または「より大きい」なら-1、0または+1を返します。最大値または最小値が見つかりません。あなたが割り当てを記述した方法は理にかなっていません。 –

答えて

1

StringはすでにComparableインターフェイスを実装していますので、あなたの仕事が正確にはわかりません。

answer = this.getName().compareTo(other.getName()); 

ObjectgetName()方法を持っていません。

answer = this.getName().compareTo(((DataSet)other).getName()); 

:あなたはDataSetでそれを実装した場合、あなたはotherの種類を変更したり、キャストを追加する必要があります。

incompatible types 
    String s = "john"; 

これは奇妙です。あなた自身のStringクラスを作成したのでしょうか?もしそうなら、あなたはString

error: cannot find symbol 
    ds.s.compareTo(a); 

DataSetにJavaのStringを割り当てることはできません何のフィールドsを持っていません。式ds.sは無効です。

error: method getMaximum in class DataSet cannot be applied to given types; 
    System.out.println("Maximum Word: " + ds.getMaximum()); 

あなたはgetMaximum()例えばに引数を追加する必要がありますgetMaximum(null)。または、メソッド宣言から引数を削除します。

0

あります。

getMaximum()(パラメータなし)を使用しようとすると、クラス内でメソッドが見つかりません。

0

ComparableまたはComparatorの実装を依頼されたことはありますか?文字列は、すでにComparableを実装して、あなたが

String firstString = "AAA"; 
int compareToValue = firstString.compareTo("BBB"); 

Aコンパレータが署名

int compare(Object o1, Object o2) 
関連する問題