Im a newbie coder and I was getting very frustrated because I keep getting compiler errors. This is a homework assignment and what I’m suppose to do is implement the Comparable class to compare any two String objects so it will return the maximum and minimum. I keep getting compiler errors and I dont exactly know why I do.
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;
}
}
the error is the getName Method
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 already implements Comparable interface, so I’m not sure what exactly your task is.
Objecthas nogetName()method. If you implemented it inDataSetyou need to change the type ofotheror add a cast:.
This is strange. Maybe you created your own
Stringclass? If so, you cannot assign java’sStringto yourStringDataSethas no fields. Expressionds.sis not valid.You need to add argument to
getMaximum()e.g.getMaximum(null). Or, remove the argument from method declaration.