This is a program that reads a file, stores it in an array, sorts it by country and then prints the contents to the screen. Iam able to sort it by id, using the "-" operand. But i would like to sort it by country. I get an error "error: bad operand types for binary operator '-'". Any help would be appreciated.
Problem:
Source code:
Problem:
public int compareTo(Object Student) throws ClassCastException {
if (!(Student instanceof ShowData))
throw new ClassCastException("Error");
String cy = ((ShowData) Student).getCountry();
int cy = ((ShowData) Student).getCountry();
return this.country - country;//This is the problem
}
Source code:
import java.io.*;
import java.util.*;
class ShowData implements Comparable {
int id;
String country;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
public int compareTo(Object Student) throws ClassCastException {
if (!(Student instanceof ShowData))
throw new ClassCastException("Error");
String cy = ((ShowData) Student).getCountry();
int cy = ((ShowData) Student).getCountry();
return this.country - country;//This is the problem
}
}
public class SortFile {
SortFile() {
int j = 0;
ShowData data[] = new ShowData[5];
try {
FileInputStream fstream = new FileInputStream("C:/student.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
ArrayList list = new ArrayList();
while ((strLine = br.readLine()) != null) {
list.add(strLine);
}
Iterator itr;
for (itr = list.iterator(); itr.hasNext();)/>/>/>/> {
String str = itr.next().toString();
String[] splitSt = str.split("\t");
String id = "", country = "";
for (int i = 0; i < splitSt.length; i++) {
id = splitSt[0];
country = splitSt[1];
}
data[j] = new ShowData();
data[j].setId(Integer.parseInt(id));
data[j].setCountry(country);
j++;
}
Arrays.sort(data);
for (int i = 0; i < 5; i++) {
ShowData show = data[i];
int no = show.getId();
String country = show.getCountry();
System.out.println(no + " " + country);
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
SortFile data = new SortFile();
}
}