将字符串实现到类似的接口

时间:2012-02-26 07:09:56

标签: java interface implementation

我是一个新手编码器,我变得非常沮丧,因为我不断收到编译器错误。这是一个家庭作业,我想要做的是实现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());

3 个答案:

答案 0 :(得分:1)

String已经实现了Comparable界面,所以我不确定你的任务到底是什么。

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

Object没有getName()方法。如果您在DataSet中实施,则需要更改other的类型或添加演员:

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

incompatible types
    String s = "john";

这很奇怪。也许你创建了自己的String课程?如果是这样,您就无法将java String分配给String

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

DataSet没有字段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)。或者,从方法声明中删除参数。

答案 1 :(得分:0)

声明方法,使它们收到对象

因此,当您尝试使用getMaximum()(没有参数)时,它在类中找不到该方法。

答案 2 :(得分:0)

您确定要求您实施Comparable或Comparator吗?字符串已经实现了Comparable,如果你调用

,它将产生一个int
String firstString = "AAA";
int compareToValue = firstString.compareTo("BBB");

比较者有签名

int compare(Object o1, Object o2)