The problem is not as simple as it looks to be on the surface. Too many things to be taken care of -- handling duplicates, sorting the ratings, associating the ratings with the names. You would have to come up with a better implementation than string arrays. Here is my humble stab at it...
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeMap;
class CompareMappings implements Comparator
{
public int compare(Object arg0, Object arg1)
{
Mappings m1 = (Mappings)arg0;
Mappings m2 = (Mappings)arg1;
return(m1.getSmartness() - m2.getSmartness());
}
}
class Mappings
{
private String name;
private int smartness;
Mappings(String rawStr)
{
rawStr = rawStr.trim();
int index = rawStr.lastIndexOf(' ');
setName(rawStr.substring(0, index + 1));
setSmartness(rawStr.substring(index + 1));
}
public String getName()
{
return name;
}
public int getSmartness()
{
return smartness;
}
void setName(String name)
{
this.name = name;
}
void setSmartness(String smartness)
{
try
{
this.smartness = Integer.parseInt(smartness);
}
catch(Exception e)
{
System.out.println("AN exception occured while settings smartness...: ");
}
}
public String toString()
{
return("Name: " + name + " Rating: " + smartness);
}
public boolean equals(Object arg0)
{
Mappings m = (Mappings)arg0;
return name.equalsIgnoreCase(m.name);
}
}
public class Temp
{
public Object[] populateFromFile(String path)
{
TreeMap map = new TreeMap(); //use TreeMap to avoid duplicates
try
{
String temp = null;
BufferedReader br = new BufferedReader(new FileReader(path));
while((temp = br.readLine()) != null)
{
Mappings m = new Mappings(temp);
map.put(m.getName(), m);
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found....");
}
catch(IOException e)
{
System.out.println("An exception occured with the input stream while reading the file...");
}
return map.values().toArray();
}
public static void main(String[] args)
{
Temp temp = new Temp();
// avoid using absolute, hardcoded paths
Object[] array = temp.populateFromFile("c:\\data.txt");
Arrays.sort(array, new CompareMappings());
for(int i = 0; i < array.length; ++i)
System.out.println(array[i].toString());
}
} ~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734