3

我在下面包含了我的所有代码(5 个课程),用于一个简单的学生数据库。

我与一个相信在NameAddressStudent类中必须包含当前存在的所有 getter 和 setter 的人共同编写了这段代码。我认为代码在没有它们的情况下将起作用,并且它们不是必需的并且应该被删除?如果他们是必要的,有人可以解释为什么或者有人可以确认他们没有必要吗?

地址类

public class Address {

private String street, area, city, country;

public Address(String street, String area, String city, String country) {
    this.street = street;
    this.area = area;
    this.street = city;
    this.country = country;
}

public void setStreet(String street) {
    this.street = street;
}

public void setArea(String area) {
    this.area = area;
}

public void setCity(String city) {
    this.city = city;
}

public void setCountry(String country) {
    this.country = country;
}

public String street() {
    return street;
}

public String area() {
    return area;
}

public String city() {
    return city;
}

public String country() {
    return country;
}

    /** Returns area, street, city and country concatenated together respectively */
public String toString() {
    return area + ", " + street + ", " + city + ", " + country + ".";
}

    }

名称类

public class Name{

private String firstName, lastName;

public Name (String firstName, String lastName){
    this.firstName = firstName;
    this.lastName = lastName;
}

public void setFirstName(String firstName){
    this.firstName = firstName;
}

public void setLastName(String lastName){
    this.lastName = lastName;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

/** Returns first name concatenated to last name */
public String toString() {
    return firstName + " " + lastName;
}

}

学生班

     public class Student {
    private Name name; // This is calling from the Name class, giving it the               name 'name'
    private Address address; // This calls from Address, giving it the name 'address'

    private char gender;

    private String course, college;

    private int gradePointAverage, id, age, level;

    public Student(int id, String firstName, String lastName, String street, String area, String city, String country, int age, char gender, String college, String course,  int level, int gradePointAverage){ //This is the list of variables called from the Student class
        this.id = id;
        this.name = new Name(firstName, lastName);
        this.address = new Address(street, area, city, country);
        this.age = age;
        this.gender = gender;
        this.college = college;
        this.course = course;
        this.level = level;
        this.gradePointAverage = gradePointAverage;
    }

    public int getId(){
        return id;
    }

    public String getName(){
        return name.toString();
    }

    public String getAddress(){
        return address.toString();
    }

    public int getAge(){
        return age;
    }

    public char getGender(){
        return gender;
    }

    public String getCollege(){
        return college;
    }

    public int getLevel() {
        return level;
    }

     public String getCourse() {
        return course;
    }

    public int getGradePointAverage() {
        return gradePointAverage;
    }

    public void printStudent() {
        System.out.println("The Student " + name.toString() + " is logged under the student ID number " + id + ".");
        System.out.println("They live at " + address.toString() + " and their age is " + age + ".");
        System.out.println("Their gender is " + gender + ".");
        System.out.println("The student studies at " + college + " attending classes in " + course + ".");
        System.out.println("Their level is " + level + " and the student grade average in points is " + gradePointAverage + ".");
        System.out.println();
    }

    }

大学社区班

    import java.util.*;

public class CollegeCommunity

    {

    private ArrayList<Student> students; // Setting up an arraylist to store student details




        public CollegeCommunity()

            {
                students = new ArrayList<Student>();
            }


        public void addStudent(Student student) // adds a student.

            {
                students.add(student); // .add method command.
            }


        public void removeStudent(int id) // deleting a student, after being passed id to locate desired student.

            {
                for (int i=0; i<students.size(); i++ ){ // using a loop to decide what student to remove by matching the student ID which was passed to the method with the student ID's on record. Once there's a match, the student will be removed (.remove).
                    if(students.get(i).getId()==id) {
                        students.remove(i);
                    }
                }
            }


        public void showStudent(int id) // same as remove above but instead using print command to view details of particular student.

            {
                for (int i=0; i<students.size(); i++ ){
                    if(students.get(i).getId()==id) {
                        students.get(i).printStudent();
                   }
                }
            }


        public void showAllStudents()

            {
                for (int i=0; i<students.size(); i++ ){ // This loop command will display ALL student details as no specific ID was passed, so it will run as long as value 'i' is less than student.size.
                    int id=students.get(i).getId();
                        showStudent(id);
                }
            }


        public void showStudentsInCourse(String course) // This will show students in a particular course.

            {
                for(int i=0; i<students.size(); i++ ){ // Loop is same as remove but comparing the string course with the course of each student. .equals is used to compare strings.
                    if(students.get(i).getCourse().equals(course)){
                        int id=students.get(i).getId();
                            showStudent(id);
                    }
                }
            }


        public int calculateGradePointAverage() // calculating the grade point average as a percentage

        {
            int total = 0;
            for (int i = 0; i < students.size(); i++ ){
                total = total + students.get(i).getGradePointAverage(); // total is calculated as it loops, each students score (getGradePointAverage).
            }

            total = total / students.size(); // final figure is total divided by the number of students, to give an average score.

            return total;

        }
}

测试系统类

    import java.util.*;

    public class TestSystem

{
   public static void main(String[] args)

    {

        Scanner sc = new Scanner(System.in);

        Student student;
        CollegeCommunity collegeCommunity = new CollegeCommunity(); // New CollegeCommunity created called 'collegeCommunity'.

        int id, age, level, gradePointAverage; // ints created for student id, age, level of course, and the grade point value

        String fName,lName, street, area, city, country, course, college; // first name, last name strings created

        char gender; // character gender created

        boolean finish = false; // boolean finish has value of False.

            do

             {
                switch(getMenu())

                {

                    case '1':


                        System.out.println();

                        System.out.print("Please enter a new Student ID > ");
                        id = sc.nextInt();
                        sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the Student's first name > ");
                        fName = sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the Student's last name > ");
                        lName = sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the street > ");
                        street = sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the area > ");
                        area = sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the city > ");
                        city = sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the country > ");
                        country = sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the age > ");
                        age = sc.nextInt();

                        sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the gender > ");
                        gender = sc.nextLine().charAt(0);

                        System.out.println();

                        System.out.print("Please enter the college > ");
                        college = sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the course > ");
                        course = sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter level > ");
                        level = sc.nextInt();

                        sc.nextLine();

                        System.out.println();

                        System.out.print("Please enter the average grade in points [0-100] > ");
                        gradePointAverage = sc.nextInt();

                        sc.nextLine();

                        System.out.println();

                        student = new Student(id, fName, lName, street, area, city, country, age, gender, college, course, level, gradePointAverage);
                        collegeCommunity.addStudent(student);


                        break;


                    case '2':


                        System.out.println();

                        System.out.print("Please enter the student ID number > ");
                        id = sc.nextInt();

                        sc.nextLine();
                        // this will delete the student selected
                        collegeCommunity.removeStudent(id);

                        System.out.println();

                        System.out.print("Student " + id + " has been deleted.");

                        System.out.println();
                        System.out.println();

                        break;


                    case '3':


                        System.out.println();

                        System.out.print("Please enter the student ID number > ");
                        id = sc.nextInt();

                        sc.nextLine();
                        // This will allow for the details of the selected student to be displayed. Calls stored data from community college.
                        collegeCommunity.showStudent(id);

                        System.out.println();
                        System.out.println();

                        break;


                    case '4':


                        System.out.println();
                        // This will show all of the students stored in the system.
                        collegeCommunity.showAllStudents();

                        System.out.println();

                        break;


                    case '5':

                        System.out.println();

                        System.out.print("Please enter the course > ");
                        course = sc.nextLine();
                        // This will show students that are enrolled in a chosen course.
                        collegeCommunity.showStudentsInCourse(course);

                        System.out.println();

                        break;

                    case '6':

                        System.out.println();

                        System.out.print("The Average grade score is " + collegeCommunity.calculateGradePointAverage() + "%");

                        System.out.println();

                        break;

                    case 'x':
                    case 'X':

                        finish = true; // boolean value changes to true if X is selected

                        System.exit(0);

                    break;

                        default:

                        System.out.println();

                        System.out.println("That is an invalid selection.");

                        System.out.println("      Please try again");

                    break;

                    }

        }while (!finish);

    }

        public static char getMenu()

            {
                Scanner sc = new Scanner(System.in);

                System.out.println();

                System.out.println("This is your community college menu");
                System.out.println("Please select from the menu options below");

                System.out.println();

                System.out.println("1 Add a Student");

                System.out.println();

                System.out.println("2 Delete a Student");

                System.out.println();

                System.out.println("3 Show details on an individual student");

                System.out.println();

                System.out.println("4 Show details on all students");

                System.out.println();

                System.out.println("5 Shows details on all students on a course");

                System.out.println();

                System.out.println("6 Display the average grade (points)");

                System.out.println();

                System.out.println("X Exit");

                System.out.println();
                System.out.println();

                System.out.print("Please make selection > ");

                return sc.next().charAt(0);
            }

    }
4

3 回答 3

10

您始终可以将属性设置为默认范围publicprotected使用默认范围并访问它们(前提是该类位于适当的包中)

myStudent.age = 9;

也就是说,使用 setter 和 getter 始终是一种好习惯。它简化了对正在设置的值的控制。例如。你可以在你的集合中打勾,这样年龄就不会小于 4

public void setAge(int age) throws Exception {
  if (age <= 3) {
    throw new Exception("Age must be more than 3");
  }
  this.age = age;
}

使用属性设置它留给程序员,他们可能会错过代码中某处的检查。稍后进行调试非常棘手。

Setter 和 getter 还有助于添加日志/断点来检查程序的行为。

大多数体面的 IDE 允许您仅根据属性自动编写 setter 和 getter 代码,所以这没什么大不了的。

作为旁注,我通常建议在需要时存储出生日期并计算年龄,因为年龄是一个会发生变化的值,而出生日期不会发生变化,并且您始终可以根据出生日期计算年龄,但不能相反。

于 2012-08-05T09:55:58.193 回答
0

我不明白为什么此时它们是必要的,尽管通过删除它们很容易验证。由于 Java 是一种编译语言,如果代码的其他部分正在使用这些方法(除非您的代码的一部分或您使用的框架使用反射),您通常会在编译时得到错误。

也许您正在编写代码的人正计划添加某种需要这些方法的对象关系映射框架?

就个人而言,我会说您永远不应该添加未使用的代码。代码库复杂性的主要贡献者是它拥有的代码行数,因此确实没有理由在其中有任何未使用的东西。

于 2012-08-05T10:01:18.347 回答
0

支持 SJuan76 的文章,并反驳另一篇文章 - 这需要说:

通过从一开始就建立和使用 getter/setter,您已经使您的代码能够在未来(如果您现在不这样做)进行所有边界检查、日志记录等,而无需客户端代码适应转换为 getter/setter。

这是一个最佳实践,可以为您节省更多时间。

您应该始终考虑您今天编写的代码将在明天为该代码建立接口。第一次就做好/灵活/可维护。

于 2012-08-05T10:10:28.263 回答