JAVA找两个最低分
(Find the two lowest scores) Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the names of the students with the lowest and second-lowest scores.哪位大神能帮忙解一下这道题,真是想了好久也想不出来。 将分数数组复制出来,排序,找到最小的两个,for-each输出两个对应的名字,思路有了吧 第一次循环找出最小的一个,第二次加一个if判定,找倒数第二小的,或者冒泡排序,然后打印出来 本帖最后由 java2python 于 2020-5-22 16:28 编辑
java有比较器的,什么排序法,你能做的过java团队?Collections集合可以排序,ArrayList也是属于集合的,Student类需要实现比较器,然后交给集合排序就行了
import java.util.ArrayList;
import java.util.Collections;
public class SortTest {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<Student>();
for(int i=0;i<5;i++) students.add(new Student(i+1,"student0"+i,(int)(Math.random()*100)));
Collections.sort(students);
for(int i=0;i<2;i++) System.out.println(students.get(i));
}
}
class Student implements Comparable<Student> {
int stuId;
String stuName;
int score;
public Student(int stuId, String stuName, int score) {
this.stuId = stuId;
this.stuName = stuName;
this.score = score;
}
@Override
public int compareTo(Student o) {
return score-o.score;
}
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
", score=" + score +
'}';
}
}
页:
[1]