【发布时间】:2017-05-23 16:32:10
【问题描述】:
在我的主类中,如何为compare 方法提供参数?因为在对象输入中询问。
它显示了一个错误:
方法 compare(String, String) 未定义 ASSIGNRES 类型;
package com.jspiders.Collection;
public class SStudent
{
int id;
String name;
int marks;
SStudent(int id,String name,int marks)
{
this.id=id;
this.name=name;
this.marks=marks;
}
}
package com.jspiders.Collection;
import java.util.Comparator;
public class Id implements Comparator
{
public int compare(Object o1,Object o2)
{
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.id==s2.id)
return 0;
else if(s1.id>s2.id)
return 1;
else
return -1;
}
}
package com.jspiders.Collection;
import java.util.Comparator;
public class Name implements Comparator
{
public int compare(Object o3,Object o4)
{
Student s3=(Student)o3;
Student s4=(Student)o4;
return s3.name.compareTo(s4.name);
}
}
package com.jspiders.Collection;
public class Marks
{
public int compare(Object o5,Object o6)
{
Student s5=(Student)o5;
Student s6=(Student)o6;
if(s5.marks==s6.marks)
return 0;
else if(s5.marks>s6.marks)
return 1;
else
return -1;
}
}
package com.jspiders.Collection;
import java.util.Scanner;
public class ASSIGNRES
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
/*While(true)
{
System.out.println("create id");
System.out.println("create name");
System.out.println("create marks");
System.out.println("enter the choice");*/
int choice=sc.nextInt();
switch(choice)
{
case 1:System.out.println("enter the id no");
int idd=sc.nextInt();
int idd1=sc.nextInt();
Object ans=(int)idd;
Object ans1=(int)idd1;
compare( ans, ans1);
break;
case 2:System.out.println("enter the name");
String name1=sc.next();
String name2=sc.next();
compare(name1,name2);
break;
case 3:System.out.println("enter the marks");
int marks1=sc.nextInt();
int marks2=sc.nextInt();
compare(marks1,marks2);
break;
}
}
}
【问题讨论】:
-
错误说明了一切:
ASSIGNRES中没有定义方法compare(String, String)。如果您尝试将上述定义的compare(Object, Object)之一移动到ASSIGNRES,您最终会得到一些ClassCastException,因为您无法将Integer转换为Student。 -
所以为了克服我必须做的事情?
-
在案例 2 和案例 3 中你比较了什么?它应该使用对象吗?如果是,它们的类型是什么?
-
知道谁得了最高分。
-
您的代码中没有可用于一对整数的比较方法...标记是整数。你想比较什么?
标签: java collections compiler-errors comparator