【发布时间】:2012-02-26 07:09:56
【问题描述】:
我是一名新手编码员,我感到非常沮丧,因为我不断收到编译器错误。这是一个家庭作业,我想做的是实现 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());
【问题讨论】:
-
我认为您误解了作业。 Comparable 是一个包含
compareTo()方法的接口,如果this对象“小于”、“等于”或“大于”某个其他对象,则该方法返回-1、0 或+1。它没有找到最大值或最小值。您描述作业的方式没有意义。
标签: java interface implementation