gpt4 book ai didi

java - 将字符串实现到类似的接口(interface)中

转载 作者:行者123 更新时间:2023-12-01 15:31:59 24 4
gpt4 key购买 nike

我是一名新手编码器,我感到非常沮丧,因为我不断收到编译器错误。这是一项家庭作业,我要做的是实现 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)。或者,从方法声明中删除参数。

关于java - 将字符串实现到类似的接口(interface)中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9451240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com