我已将下面的所有代码(5个类)包含在一个简单的学生数据库中。
我认为这段代码与认为在名称,地址和学生类中的人有关,所以必须包含所有的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;
}
}
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);
}
}
答案 0 :(得分:10)
您始终可以将属性设置为public
或protected
或使用默认范围并访问它们(前提是该类位于相应的包中)
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代码,所以这不是什么大问题。
作为附注,我通常会建议存储出生日期并在需要时计算年龄,因为年龄是一个值,而出生日期不会改变,你可以随时计算出生日期的年龄,但不能相反。
答案 1 :(得分:0)
我无法理解为什么它们在这个时候是必要的,尽管这很容易通过删除来验证。由于Java是一种编译语言,如果代码的其他部分使用这些方法,则通常在编译时会出现错误(除非您使用的部分代码或框架使用反射)。
也许您正在编码的人计划添加某种需要这些方法的对象 - 关系 - 映射框架?
我个人会说你永远不应该添加未使用的代码。代码库复杂性的主要影响因素是它拥有的代码行数,因此没有理由在其中有任何未使用的代码。
答案 2 :(得分:0)
为了支持SJuan76的写作,并反对另一篇文章 - 这需要说:
通过从一开始就建立和使用getter / setter,您已经启用了代码,以便将来拥有所有边界检查,日志记录等(如果您现在不执行这些操作),而无需客户端代码适应转换TO getter / setters。
这是一种最佳实践,可以为您节省更多时间。
您应该始终认为您今天编写的代码明天将为该代码建立接口。第一次正确/灵活/可维护。