Reputation: 11
Error:
Sortbyname cannot be resolved to a type in java
I am using the Comparator interface method by sorting the name and score for cricket players using in java.
I am a beginner in java
package javapractice2;
import java.util.*;
import java.io.*;
public class Player {
String player_name;
int player_score;
public Player(String member, int score) {
this.player_name = member;
this.player_score = score;
}
}
/Comparator/
package javapractice2;
import java.util.*;
public class NameComparator {
public class Sortbyname implements Comparator<Player>{
public int compare(Player a, Player b){
return a.player_name.compareTo(b.player_name);
}
}
}
/Main method in java/
package javapractice2;
import java.util.ArrayList;
import java.util.Collections;
public class Mainclass {
public static void main(String[] args) {
ArrayList<Player> ply = new ArrayList<Player>();
ply.add(new Player ("kuldeep", 85));
ply.add(new Player ("jadeja", 75));
ply.add(new Player ("dohni", 48));
ply.add(new Player ("kozhi", 78));
ply.add(new Player ("raina", 48));
ply.add(new Player ("sachin", 85));
ply.add(new Player ("yuvaraj", 100));
ply.add(new Player ("Ajinkya", 85));
ply.add(new Player ("baji", 75));
ply.add(new Player ("hardik", 55));
Collections.sort(ply, new Sortbyname());
for(int i=0; i<ply.size(); i++){
System.out.println(ply.get(i));
}
}
}
Upvotes: 0
Views: 631
Reputation: 335
Sortbyname is a nested class,
you need to create object for it as bellow,
new NameComparator.new Sortbyname();
go through below link for more information https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Upvotes: 1
Reputation: 797
Everything in your code is fine except the following inner class style code:
public class NameComparator {
public class Sortbyname implements Comparator<Player>{
So change this class as following:
Sortbyname.java
package javapractice2;
import java.util.Comparator;
public class Sortbyname implements Comparator<Player> {
public int compare(Player a, Player b) {
return a.player_name.compareTo(b.player_name);
}
}
Also add a toString()
method in Player.java for better output printing:
package javapractice2;
public class Player {
String player_name;
int player_score;
public Player(String member, int score) {
this.player_name = member;
this.player_score = score;
}
@Override
public String toString() {
return "Player [player_name=" + player_name + ", player_score=" + player_score + "]";
}
}
Otherwise, if you want to keep your code, then update the following in your Mainclass.java:
Collections.sort(ply, new NameComparator().new Sortbyname());
Upvotes: 2