我是一個新手編碼器,我變得非常沮喪,因爲我不斷收到編譯器錯誤。這是一項家庭作業,我想要做的是實現Comparable類來比較任何兩個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());
我想你誤會分配將產生一個int。 Comparable是一個包含'compareTo()'方法的接口,如果'this'對象是「小於」,「等於」或「大於」某個其他對象,則返回-1,0或+1。它沒有找到最大值或最小值。你描述任務的方式沒有意義。 – 2012-02-26 07:29:49