2017-02-17 30 views
0

我是一個java初學者,(原諒我的英文不好)我想比較一下有(名字,分數)的學生對象。並以最高分返回學生姓名。 我在學生課中有getScore和getName。java在不同的ojbects中的歸因

public String tallest() { 

    //set a defaut value 
    int score = 0; 
    for(Student student: this.student) { 
     // compare which student has highest score 
     if(student.getScore() < score) { 
      score = student.getScore(); 
      String name = ((String)student.getName()); 
     } 
    } 
    return name; 
} 

另一個問題是關於如何與高於80

public ArraryList<student>goodStudent<int level> { 
    int level = 80; 
    for(Student student: this.student) { 
    if(student.getScore > 80) { 
    (don't know how to do here >.<) 

    return list; 
} 
+0

如果你想得分最高的,你應該檢查'如果(student.getScore()>評分){''不<' – alfasin

+0

至於第二個,你應該創建一個空的列表,並添加對於任何等級> =的學生。 – alfasin

回答

3
public String tallest() { 
    return Collections.max(students, 
      Comparator.comparingInt(Student::getScore)).getName(); 
} 

public List<Student> goodStudent(int level) { 
    return student.stream() 
      .filter(s -> s.getScore() > level) 
      .collect(Collectors.toList()); 
} 
0

對於你的第一個問題(姓名,分數)返回所有的學生對象,你可以使用Java Comparator,建ScoreComparator根據他們的分數比較Student。然後使用Collections.sort(students, new ScoreComprator())排序列表,你可以從它那裏得到的最高分(取決於你如何排序是否按升序或漸漸收窄順序)

對於第二個問題,你可以實例化另一個的ArrayList,然後遍歷列表students,如果student.getScore() > 80將其添加到新的創建列表。

+0

儘管OP說「比較學生對象」,但他並沒有真正比較它們,而是試圖通過評分標準「過濾」它們 – alfasin

0

希望得到這個幫助。任何問題隨時問。

import java.util.ArrayList; 

class Student{ 
    private String name; 
    private int score; 

    public Student(String name, int score){ 
     this.name = name; 
     this.score = score; 
    } 

    public int getScore() { 
     return score; 
    } 

    public void setScore(int score) { 
     this.score = score; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 

public class Test{ 

    public static void main(String[] argv) throws Exception { 
    Student[] students = {new Student("Jhon", 78), new Student("Kevin", 90), new Student("Max", 100)}; 

    Student maxScore = GetMaxScore(students); 
    System.out.println("Max Score:"); 
    System.out.println(maxScore.getScore()); 

    ArrayList<Student> studentsOverVal = GetScoreOverVal(students, 80); 
    System.out.println("Students with score over 80: "); 
    for(Student student: studentsOverVal) { 
     System.out.println(student.getName()); 
     } 

    } 

    private static Student GetMaxScore(Student[] students) { 
    Student max = students[0]; 
    for(Student student: students) { 
     if(student.getScore() > max.getScore()) 
      max = student; 

     } 
    return max; 
    } 

    private static ArrayList<Student> GetScoreOverVal(Student[] students, int val) { 
    ArrayList<Student> overVal = new ArrayList<>(); 
    for(Student student: students) { 
     if(student.getScore() >= val) 
      overVal.add(student); 
     } 
    return overVal; 
    } 

}