java - 如何解决: compareTo >> cannot find symbol

标签 java object interface compare compareto

这是一项家庭作业。然而,我已经编写了作业的大部分内容。只有这一个障碍。我也是 Java 新手,所以我的术语可能有点偏差。

所以我有5种类型: 老师提供:

  • NameInterface,即Name的接口(interface)文件
  • 名称,使用 2 个私有(private)字符串(名字和姓氏)来表示名字和姓氏
  • StudentInterface,即Student的接口(interface)文件
  • StudentTest,这是用于测试的主要方法

大部分是老师提供的,我只需要修复compareTo()。其他所有内容(如构造函数、字段等)均已完成:

  • 学生,使用 fullName(名称接口(interface))和字符串城市

Name 类有一个compareTo() 重写,它使用Java 的内置compareTo 来比较第一个和另一个第一个

  public int compareTo(Object other)
  {
  int result = last.compareTo(((Name)other).last);

  if (result == 0)
  {   
      // last names are equal; check first
     result = first.compareTo(((Name)other).first);
  }  // end if 

  return result; 
} // end compareTo

Student类有一个compareTo(),它使用Name类compareTo来比较这个Name和其他Name以及这个城市和其他城市

  public int compareTo(Object other)
  {
  Student localStudent = (Student) other;
  int result = (fullName.getName()).compareTo((localStudent.getName()).getName());

  if (result == 0)
  {   
      // last names are equal; check first
     result = city.compareTo(localStudent.getCity());
  }  // end if 

  return result; 
  } // end compareTo

我尝试在StudentTest中调用Student类的compareTo,但它说找不到符号。

  StudentInterface si = new Student();
  si.setCity("Kingston");
  NameInterface ni = new Name("Andrew","Pletch");
  si.setName(ni);

  StudentInterface si2 = new Student();
  si2.setCity("Kingston");
  NameInterface ni2 = new Name("Aram","Agajanian");
  si2.setName(ni2);
  System.out.println(" compare as (should be +ve) " + si.compareTo(si2));

错误是:

StudentTest.java:27: error: cannot find symbol
  System.out.println(" compare as (should be +ve) " + si.compareTo(si2));        
                                                        ^
symbol:   method compareTo(StudentInterface)
location: variable si of type StudentInterface
1 error

我的结论是“Object other”不符合“StudentInterface”。我该如何解决这个问题?谢谢大家。

最佳答案

将compareTo添加到接口(interface)中。使用的所有方法都必须用变量的类型表示。 si 是 StudentInterface 类型,因此只能使用在 StudentInterface 上声明的方法。

关于java - 如何解决: compareTo >> cannot find symbol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33336316/

相关文章:

C++ 如何区分异构集合中的特定对象类型?

c# - .Net 接口(interface)何时被视为等效?

java - 在同一个 osgi 包中可以有两个服务接口(interface)吗?

java - 使用 Java 查找矩阵最小值最大值的其他方法

java - 嵌入式 Switch Case 语句

Java - 在另一个类中使用一个类的输出

c# - 泛型类型的转换无效

java - 如何在一个应用程序中创建 2 个操作栏?

c++ - 多个 Dll 通过 "main"dll 相互调用函数

java - 有没有办法使用循环来改进这段代码?