【问题标题】:Using a for loop to print out students and their grades from highest to lowest , using an object使用 for 循环从最高到最低打印学生和他们的成绩,使用一个对象
【发布时间】:2018-05-16 17:45:07
【问题描述】:

因此,在这个项目中,我要询问班级的学生人数、每名学生的录取情况以及与他们相关的年级。 myStudents[i] 然后保存每个学生的姓名和他们的成绩。我现在遇到的问题是我的两个选择排序。我应该按成绩排列每个学生(从最高到最低。我认为我在 public static 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;
    }
}   

一旦我开始合并 get 和 objects,我往往会有点困惑。再次,非常感谢任何建议。

【问题讨论】:

  • 你的意思是打印出像Stream.of(strings).forEach(System.out::println)这样的for循环
  • 如果您不打算将 name 和 score 设为私有,那么制定 get 方法是没有意义的。您可以使用 student.score 和 student.name 访问它们。另外,请确保您考虑到名称。如果成绩相同,您可能应该按姓名的字母顺序排序。

标签: java object this selection-sort


【解决方案1】:

所以您的问题是如何打印您的 Student 数组,该数组按选择排序排序,对吧?

在您的 main 方法中,在循环条件后(在创建学生数组时)添加此代码。

selectionSort(myStudents);

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

该代码将打印您的学生数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多