[英]implementing string into comparable interface
我是一个新手编码员,由于不断出现编译器错误,我感到非常沮丧。 这是一项家庭作业,我想做的是实现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());
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)
。 或者,从方法声明中删除参数。
声明了方法,以便它们接收一个Object 。
因此,当您尝试使用getMaximum()
(不带参数)时,在类中找不到该方法。
您确定要求您实施Comparable或Comparator吗? 字符串已经实现Comparable,并且如果您调用则将产生一个int
String firstString = "AAA";
int compareToValue = firstString.compareTo("BBB");
比较器具有签名
int compare(Object o1, Object o2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.