2015-09-24 31 views
0

聲明:我是一名非常早期的學生,並且正在努力學習java。請告訴我,如果我遺漏了任何重要的信息。我正在寫一個程序,提示用戶做一個鏈接列表(添加,刪除,更改值等)的各種操作,而不是存儲一個字符串或一些原始數據類型我正在存儲的類型學生的對象(其中基本上包含一個字符串作爲學生的名字和他們的測試分數的整數),並堅持如何找到最大的考試分數,因爲我不能找到最高的學生。java - 從鏈接列表中找到最大值

任何幫助,將不勝感激。

回答

0

那麼你可以有兩個變量,一個作爲currentScore,另一個作爲newScore。然後遍歷每個學生對象,獲取測試值,然後進行比較。如果新分數較低,則保持最新。如果新分數較高,請用新分數替換當前分數,並繼續遍歷。當遍歷列表時,得到的分數最高

0

您可以按照其他描述進行迭代,也可以使用Collections.max方法。要使用此方法,您的學生課程應實施comperable界面。

public class Student implements Comparable<Student> 

,你需要compareTo方法添加到類:

@Override 
public int compareTo(Student student) 
{ 
    if (this.score > student.score) 
    { 
     return 1; 
    } 
    if (this.score < student.score) 
    { 
     return -1; 
    } 
    else 
    { 
     return 0; 
    } 
} 

現在,當你寫Collections.max(list)你會得到分數最高的學生。

0

我寫了一個簡單的程序來匹配你的情況。

主類:

import java.util.*; 
import java.lang.Math; 

public class FindHighestScore 
{ 
    public static void main(String[] args) 
    { 
    LinkedList<Student> studentLinkedlist = new LinkedList<Student>(); 

    studentLinkedlist.add(new Student("John",1)); // Adding 5 students for testing 
    studentLinkedlist.add(new Student("Jason",5)); 
    studentLinkedlist.add(new Student("Myles",6)); 
    studentLinkedlist.add(new Student("Peter",10)); // Peter has the highest score 
    studentLinkedlist.add(new Student("Kate",4)); 

    int temp = 0; // To store the store temporary for compare purpose 
    int position = 0; // To store the position of the highest score student 

    for(int i = 0; i < studentLinkedlist.size(); i ++){ 
     if(studentLinkedlist.get(i).getScore() > temp){ 
     temp = studentLinkedlist.get(i).getScore(); 
     position = i; 
     } 
    } 

    System.out.println("Highest score is: " + studentLinkedlist.get(position).getName()); 
    System.out.println("Score: " + studentLinkedlist.get(position).getScore()); 


    } 
} 


學生構造類:

public class Student 
{ 
    String name; 
    int score; 

    Student(){ 
    } 

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

    String getName(){ 
    return this.name; 
    } 

    int getScore(){ 
    return this.score; 
    } 
} 


上述程序產生的結果如下:

Highest score is: Peter 
Score: 10