我试图冒泡排序数组列表,我不断收到错误bad operand types for binary operator '>'我试图按数字顺序对它进行排序,以获得下面列出的测试分数.我是java的新手,对于该怎么做我很困惑.我很确定整数存储在列表中.
我的代码是:
public static void sort(){
int k = 0;
boolean exchangeMade = true;
while((k < classroom.size() - 1) &&exchangeMade){
exchangeMade = false;
k++;
for (int j = 0; j < classroom.size() - k; j++)
if(classroom.get(j) > classroom.get(j+1)){
swap(j, j+1);
swap(classroom, j, j+1);
exchangeMade = true;
}
}
Run Code Online (Sandbox Code Playgroud)
该程序的其余代码是
public class Test {
private static FileInputStream inFile;
private static InputStreamReader inReader;
private static BufferedReader reader;
private static List<Student> classroom =
new ArrayList<Student>(); // ArrayList to store the classroom.
public static void main(String args[]) throws IOException {
initFile();
getData();
System.out.print(classroom); //output of the complete class.
sort();
System.out.print(classroom); //output after sorting.
inFile.close();
}
// preparing the file for input
public static void initFile() throws IOException {
inFile =
new FileInputStream(
"C:\\Users\\clamanna\\Google Drive\\Senior\\AP COMP SCI\\!!VHSJava\\!!APCSDATA\\truefalse.txt");
inReader = new InputStreamReader(inFile);
reader = new BufferedReader(inReader);
}
// Separate the id from the answers and store the answers in an array.
public static void getData() throws IOException {
String line = reader.readLine(); //Seed
String[] answerkey = new String[10]; //Store the answer key from the first line of the txt file.
for (int i = 0;
i < answerkey.length;
i++) { // take that line and place each answer in an array.
answerkey[i] = line.substring(i, i + 1);
}
line = reader.readLine(); // read the following line of the txt file.
while (line != null) // Read and create a student for each line.
{
String[] answers = new String[10];
StringTokenizer strTkn = new StringTokenizer(line);
String id = strTkn.nextToken();
String answerline = strTkn.nextToken();
for (int i = 0; i < answers.length; i++) {
answers[i] = answerline.substring(i, i + 1);
}
Student stu = new Student(id, answers);
stu.grade(answerkey, answers);
classroom.add(stu);
line = reader.readLine(); //updating what is being read
}
}
}
Run Code Online (Sandbox Code Playgroud)
关系运算符喜欢>和<仅定义数字基元类型,如int和double.
您还可以使用它们相当于盒装类型,如Integer和Double,因为这些可以自动拆箱到原语.
要比较对象,您应该使用以下Comparable.compareTo方法:
classroom.get(j).compareTo(classroom.get(j+1)) > 1
Run Code Online (Sandbox Code Playgroud)
注意,这需要你的元素来实现Comparable接口-这常见的类型,如Integer,Double等做的,以及之类的东西String(这与字典顺序一致实现它).
如果您的元素类没有实现Comparable(并且您无法对其进行更改以实现它),则可以使用Comparable被调用的"外部"形式Comparator,这是这样的接口:
interface Comparable<T> {
int compare(T a, T b);
}
Run Code Online (Sandbox Code Playgroud)
你不加入,你想比较类-你实现这个接口作为一个单独的类,这样compare如果你考虑返回负数,零或正数a < b,a == b并a > b分别.
然后,你会使用:
comparator.compare(classroom.get(j), classroom.get(j + 1)) > 1
Run Code Online (Sandbox Code Playgroud)
where comparator是实现类的实例Comparator<Student>.(实际上,它可以Comparator<? super Student>,但现在不要担心太多).
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |