【问题标题】:implementing string into comparable interface将字符串实现为可比较的接口
【发布时间】: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


【解决方案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)。或者,从方法声明中删除参数。

【讨论】:

    【解决方案2】:

    声明这些方法,以便它们接收一个对象

    所以当你尝试使用getMaximum()(不带参数)时,它在类中找不到方法。

    【讨论】:

      【解决方案3】:

      您确定您被要求实现 Comparable 或 Comparator 吗?字符串已经实现了 Comparable 并且如果你调用会产生一个 int

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

      比较器有签名

      int compare(Object o1, Object o2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-29
        • 2015-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-08
        • 1970-01-01
        相关资源
        最近更新 更多