在我的主类中,如何为 compare
方法提供参数?因为正在询问对象输入。
它向我显示了一个错误:
The method compare(String, String) is undefined for the type 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;
}
}
}
最佳答案
您正在定义 Comparator
子类,但并未实际使用它们。
String name1=sc.next();
String name2=sc.next();
compare(name1,name2);
我假设您的意思是在 Name
中调用 compare
方法,如下所示:
Name nameComparator = new Name();
Student student1 = new Student(0, sc.next(), 0);
Student student2 = new Student(0, sc.next(), 0);
nameComparator.compare(student1,student2);
这将根据 name
字段的值返回哪个学生更优秀。
您拥有的 Comparator
子类采用 Student
实例并根据特定字段对它们进行比较。您无法直接使用字段值调用它们,您必须创建 Student
实例进行比较。
关于java - ASSIGNRES 类型的比较方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44140408/