gpt4 book ai didi

java - 此代码运行是否需要 getter 和 setter?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:49:15 24 4
gpt4 key购买 nike

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

我与相信在 NameAddressStudent 类中有必要包含所有 getter 的人共同编写了这段代码和目前在那里的二传手。我认为代码在没有它们的情况下也能正常工作,并且它们不是必需的并且应该被删除?如果它们是必要的,有人可以解释为什么或者有人可以确认它们不是必需的吗?

地址类

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

}

学生类(class)

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

}

最佳答案

您始终可以将属性设置为 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 代码,所以这没什么大不了的。

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

关于java - 此代码运行是否需要 getter 和 setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11815449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com