簡體   English   中英

使用for循環使用對象從最高到最低打印出學生及其成績

[英]Using a for loop to print out students and their grades from highest to lowest , using an object

因此,在這個程序中,我要詢問每班學生的人數,每個學生的人數以及與他們相關的成績。 然后,myStudents [i]會保存每個學生的姓名和他們的成績。 我現在遇到的問題是我的兩個selectionSort。 我應該按等級排列每個學生(從最高到最低。我認為我在公共靜態void selectionSort(student [] myStudents)中做得正確,但是我不確定如何使用for循環將其打印出來當我打電話給selectionSort時,將不勝感激任何向我指出正確方向的建議,謝謝!

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;
    }
}   

一旦開始合並獲取和對象,我往往會感到困惑。 同樣,任何建議都將不勝感激。

所以您的問題是如何打印按選擇排序排序的Student數組,對嗎?

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

selectionSort(myStudents);

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM