学生对象数组java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21367252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:19:44  来源:igfitidea点击:

Array of Student objects java

javaarrays

提问by JP Hochbaum

Just to give a run down of what I am trying to do, here is the HW my professor gave me:

只是为了简要介绍我正在尝试做的事情,这是我的教授给我的硬件:

  1. Define a class Student which extends Person. It adds the attributes
  1. 定义一个扩展Person 的类Student。它添加了属性

Int Test1, test2, test3 Double average String grade

Int Test1, test2, test3 双平均字符串等级

It has methods computeaverage() and calculategrade(). The grades are based on the average, with above 90 an A, 80 to 90 a B, 70 to 80 a C etc. All other attributes have a set and a get.

它有方法computeaverage() 和calculategrade()。成绩基于平均分,90 分以上为 A,80 至 90 分为 B,70 至 80 分为 C 等。所有其他属性都有一套和一套。

  1. Write an application that uses an array of type student of size 20. The program prompts the user for how many students are in the class and then allows them to enter the students and their test scores, then calculates their grades and prints out the list of students and their grades.
  1. 编写一个使用大小为 20 的 student 类型数组的应用程序。该程序提示用户班上有多少学生,然后允许他们输入学生和他们的考试成绩,然后计算他们的成绩并打印出学生名单学生和他们的成绩。

That being said...

话虽如此...

On Thursday I saw a classmates code that he got from the teacher and he had something that I haven't seen before in my student class on line 37 (Student Constructor). Instead of having getters and setters he had code similar to what I have at line 37. But I have no idea what he did and the correct coding. So I was hoping someone here could tell me what I am doing wrong and how this code can get away without using getter and setter methods???

星期四我看到了他从老师那里得到的一个同学代码,他在第 37 行(Student Constructor)的学生课上有一些我以前从未见过的东西。他的代码与我在第 37 行的代码相似,而不是使用 getter 和 setter。但我不知道他做了什么以及正确的编码。所以我希望这里有人能告诉我我做错了什么,以及如何在不使用 getter 和 setter 方法的情况下摆脱这段代码???

public class Person {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {



        Scanner kbd = new Scanner(System.in);
        Student newStudent = new Student();
        int size;

        System.out.println("Enter the amount of students:");
        size = kbd.nextInt();
        Student[] myStudent = new Student[size];
        String firstName;
        String lastName;
        int test1, test2, test3;
        Student s;

        for (int i=0; i < size; i++)
        {

        System.out.println("Enter first name of student: " + i);
        firstName = kbd.next();

        System.out.println("Enter last name if student: " +i);
        lastName = kbd.next();

        System.out.println("Please Enter first test score: ");
//        JOptionPane.showInputDialog("Please enter first test score:");
        test1= kbd.nextInt();

        System.out.println("Please enter second test score");
//        JOptionPane.showInputDialog("Please enter second test score:");
        test2= kbd.nextInt();

        System.out.println("Please enter third test score");
//        JOptionPane.showInputDialog("Please enter third test score:");
        test3=kbd.nextInt();

//        s = new Student (test1, test2, test3, firstName, lastName);
        myStudent[i].setTest1(test1);
        myStudent[i].setTest2(test2);
        myStudent[i].setTest3(test3);
        myStudent[i].setfName(fName);
        myStudent[i].setlName(lname);


        }
        for (int i = 0; i < size; i++)
        {
            System.out.println(myStudent[i].getGrade());
        }



    }
}


public class Student extends Person{

    int test1, test2, test3;
    double average;
    String grade, firstName, lastName;


    public Student() 
    {
        test1 = 0;
        test2 = 0;
        test3 = 0;
        average = 0;


    }




    public Student(int test1, int test2, int test3, String firstName, String lastName) 
    {
        this.test1 = test1;
        this.test2 = test2;
        this.test3 = test3;

        this.setfirstName = firstName;
    }


    public double computeAverage()
    {
        average = (test1 + test2 + test3)/3;
        return average;

    }

    public String calculateGrade()
    {
        average = computeAverage();

        if (average < 60){
            grade = "F";}
        else if (average < 70){
            grade = "D";}
        else if (average < 80){
            grade = "C";}
        else if (average < 90){
            grade = "B";}
        else {
            grade = "A";
        }
        return grade;
    }

    public int getTest1() {
        return test1;
    }

    public void setTest1(int test1) {
        this.test1 = test1;
    }

    public int getTest2() {
        return test2;
    }

    public void setTest2(int test2) {
        this.test2 = test2;
    }

    public int getTest3() {
        return test3;
    }

    public void setTest3(int test3) {
        this.test3 = test3;
    }

    public double getAverage() {
        return average;
    }

    public void setAverage(double average) {
        this.average = average;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }



}

回答by Reinstate Monica

Typically, you'll want to encapsulate your fields as much as possible. This means make these

通常,您会希望尽可能多地封装您的字段。这意味着让这些

int test1, test2, test3;
double average;
String grade, firstName, lastName;

things private. You'll then need getters and setters to access them from outside the class. That's a good thing. However, from inside the class, you can use them without getters or setters no problem.

私事。然后,您将需要 getter 和 setter 来从类外部访问它们。这是好事。但是,从类内部,您可以在没有 getter 或 setter 的情况下使用它们,没问题。

Does this answer your question? I have no idea what is on line 37, as you didn't provide numbering. :)

这回答了你的问题了吗?我不知道第 37 行是什么,因为您没有提供编号。:)

Edit: In case you don't know, constructors can be overloaded. You have two different constructors, one with parameters, one without. You can choose which one you want to use to construct the class, you probably want to be using the second one.

编辑:如果您不知道,构造函数可以被重载。你有两种不同的构造函数,一种有参数,一种没有。您可以选择要使用哪一个来构造类,您可能希望使用第二个。

If you have need for both constructors, one complete one and another one that uses default values, you might want to contemplate referencing the second constructor from inside the first, to avoid duplication of code. Like so:

如果您需要两个构造函数,一个完整的,另一个使用默认值的,您可能需要考虑从第一个构造函数内部引用第二个构造函数,以避免代码重复。像这样:

public Student() {
    this(0,0,0);
}

public Student(int test1, int test2, int test3, String firstName, String lastName) {
    this.test1 = test1;
    this.test2 = test2;
    this.test3 = test3;
    this.average = 0;
    this.firstName = firstName;
    this.lastName = lastName;
}

回答by duffymo

Your Person class is wrong. It has no attributes or methods. There's no reason to extend it, because it brings nothing to the party.

你的 Person 类是错误的。它没有属性或方法。没有理由延长它,因为它没有给党带来任何东西。

You don't need getters or setters if the attribute is visible to the public, but that doesn't mean it's a good idea.

如果属性对公众可见,则不需要 getter 或 setter,但这并不意味着这是一个好主意。

Try thinking more like this:

尝试更像这样思考:

public class Person {
    protected String firstName;
    protected String lastName;

    public Person(String f, String l) {
        this.firstName = f;
        this.lastName = l;
    }

    public String getFirstName() { return this.firstName; }
    public String getLastName() { return this.lastName; }
}

public class Student extends Person {
    public static final int MAX_GRADES = 3;
    private int numGrades = 0;
    private int maxGrades;
    private int [] grades;

    public Student(String f, String l) {
        this(f, l, MAX_GRADES);
    }

    public Student(String f, String l, int maxGrades) {
        super(f, l);
        this.maxGrades = (maxGrades > 0) ? maxGrades : MAX_GRADES;
        this.grades = new int[this.maxGrades];   
    }

    public void addGrade(int grade) {
        if (this.numGrades < this.maxGrades) {
            this.grades[numGrades++] = grade;
        }
    }

    public double getAverageGrade() { 
        double average = 0.0;
        if (this.numGrades > 0) {
            for (int i = 0; i < this.numGrades; ++i) {
                average += grade[i];
            }
            average /= this.numGrades;
        }
        return average;
    }
}

回答by Christian

There are two constructorsin Studentclass:

两个构造函数Student类:

  • Constructor without parameters
  • Constructor with paramers (int,int,int,String,String)
  • 无参数构造函数
  • 带参数的构造函数 ( int, int, int, String, String)

This is called method/function overloading. You can declare many method with the same name, but the signature has to change. In other words, it has to have different parameters (so the compiler will know which version of the method to use).

这称为方法/函数重载。您可以声明许多具有相同名称的方法,但签名必须更改。换句话说,它必须有不同的参数(这样编译器就会知道要使用哪个版本的方法)。

So you have one constructor without parameters, that just set test1, test2, test3and averageto 0. And you have this constructor:

所以,你有一个构造函数不带参数,那刚刚成立test1test2test3average为0。你有这样的构造函数:

public Student(int test1, int test2, int test3, String firstName, String lastName) 
{
    this.test1 = test1;
    this.test2 = test2;
    this.test3 = test3;
    ...
}

that receives 4parameters and assigns them to the respective fields.

接收4参数并将它们分配给相应的字段。

Notethat you should initialize averagein the constructor too, as well as set firstNameand lastName:

请注意,您也应该average在构造函数中初始化,以及设置firstNamelastName

this.average = 0; // Or maybe 'this.average = computeAverage();'
this.firstName = firstName;
this.lastName = lastName;

回答by A Parikh

His instance variables (the variables declared at the beginning of Student) were public, which allowed him to access and change them directly without the use of setters and getters. Normally, these variables are private, requiring methods to access/change them.

他的实例变量(Student 开头声明的变量)是public,这使他可以直接访问和更改它们,而无需使用 setter 和 getter。通常,这些变量是私有的,需要方法来访问/更改它们。