2017-12-02 171 views
0

因此,在此程序中,我要求每班學生的學生人數以及與其相關的年級。 myStudents [i]然後保存每個學生的名字和他們的成績。我現在遇到的問題是與我的兩個selectionSort。我應該按照等級來安排每個學生(從最高到最低),我認爲我在public static void selectionSort(student [] myStudents)中做了正確的操作,但是我不知道如何使用for循環打印出來當我打電話選擇排序。任何意見,指出我在正確的方向將不勝感激。謝謝!使用for循環打印出學生及其成績從高到低,使用對象

import java.util.Scanner; 
public class Final4{ 

    public static void main(String[] args) { 



     Scanner myInput=new Scanner(System.in); 
     System.out.print("Enter the size of the class: "); 
     int num = myInput.nextInt(); 


     int array[] = new int[num]; 
     double score; 
     student[] myStudents = new student[num]; 


     for (int i = 0 ; i < array.length; i++) { 
      System.out.print("Please enter a student name: "); 
      myInput.useDelimiter(System.getProperty("line.separator")); 
      String s; 
      s = myInput.next(); 

      System.out.print("Please enter " + s +"'s score: "); 

      score = myInput.nextDouble(); 

      myStudents[i] = new student(s, score); 

     } 

    } 
    selectionSort() 


    public static void selectionSort(student[] myStudents) { 


     for (int i = myStudents.length-1; i>0; i--){ 

      int maxIndex = 0; 
      student max = myStudents[0]; 

      for (int j=1; j<=i; j++) 

       if (myStudents[j].getScore() > (max.getScore())) { 
        maxIndex = i; 
       } 

      student temp = myStudents[i]; 

      myStudents[i] = myStudents[maxIndex]; 

      myStudents[maxIndex] = temp; 


     } 

    } 
} 
class student { 
    String name; 
    double score; 

    student(String name, double score) { 
     this.name = name; 
     this.score = score; 
    } 

    public double getScore() { 
     return score; 
    } 
    public String getName() { 
     return name; 
    } 
} 

我往往會得到一點點困惑,一旦我馬上就能得到和對象。同樣,任何建議是極大的讚賞。

+0

你的意思是打印出一個類似'Stream.of(strings).forEach(System.out :: println)'的for-loop' – ifly6

+0

如果你不打算命名和評分。你可以用student.score和student.name訪問它們。另外,請確保您考慮名字。如果成績相同,您應該按字母順序排序。 – Meepo

回答

1

所以你的問題是如何打印的Student陣列是由選擇排序排序,對吧?

在您的主要方法上,在循環條件(創建Student數組)之後添加此代碼。

selectionSort(myStudents); 

for(Student s: myStudents) { 
    System.out.println(s.getName() + " " + s.getScore()); 
} 

該代碼將打印您的學生數組。