在数组中排序学生考试成绩

时间:2017-01-14 21:03:37

标签: java algorithm

我给出一个整数N,它是将输入的测试分数。对于每一行N,将有一个学生姓名跟随他们的考试成绩。我需要计算他们的考试成绩和总和。打印出第二小的学生姓名。

1 个答案:

答案 0 :(得分:0)

所以,我要做的是为学生创建一个类数组。该类将有两个名称和分数的实例变量。然后,当完成所有输入后,您需要做的就是获取它们。这是我为此提出的代码。

import java.util.*;

public class testScores {

    public static void main(String[] args){


        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        Student[] students = new Student[n];
        for(int i = 0; i < n; i++){
            students[i] = new Student();
            System.out.print("Enter the student's name");
            students[i].setName(scan.next());
            scan.nextLine();
            System.out.print("Enter the student's score");
            students[i].setScore(scan.nextInt());
            scan.nextLine();
        }

        int total = 0;
        int smallest_name = 0;
        for(int i = 0; i < n; i++){
            total+=students[i].getScore();
            if(students[i].getName().length() < students[smallest_name].getName().length())
                smallest_name = i;
        }

        int second_smallest = 0;
        for(int i = 0; i < n; i++){
            if(students[i].getName().length() > students[smallest_name].getName().length() && students[i].getName().length() < students[second_smallest].getName().length())
                second_smallest = i;
        }

        System.out.println("The sum of the scores is: " + total);
        System.out.println("The second smallest name is: " + students[second_smallest].getName());

    }
}

class Student{

    private String name;
    private int score;

    public Student(){}

    public void setScore(int n){
        score = n;
    }

    public void setName(String n){
        name = n;
    }

    public int getScore(){
        return score;
    }

    public String getName(){
        return name;
    }

}