我想获得类似于此的输出 -
John Smith已添加到学生列表中Tom Will已添加到学生列表中,您的姓名已添加到学生列表中--Begin--姓名:John Smith电子邮件:js@qmul.ac.uk年份:2008姓名:汤姆将发送电子邮件:tw@qmul.ac.uk年份:2007姓名:您的姓名电子邮件:您的电子邮件年份:您的年份 - 结束 - 汤姆威尔已从学生名单中删除 - 开头 - 姓名:约翰史密斯电子邮件:js@qmul.ac.uk年份:2008姓名:您的姓名电子邮件:您的电子邮件年份:您的年份 - 结束 -
但它印刷得很混乱 . 我的代码在哪里出错?
代表学生的 class :
public class Student {
private String name;
private String email;
private int year; //year of registration to the course
/**
* Constructor
*
*@param name, email and year of registration
*/
public Student(String name, String email, int year){
this.name = name;
this.email = email;
this.year = year;
}
/**
* get the name
*
*@return the name
*/
public String getName(){
return name;
}
/**
* A toString() method to give a String representation of a Student
*
*@return The String representation of a Student
*/
public String toString(){
return "Name:" + name +" Email:" + email + " Year:" + year;
}
}
public class StudentList {
private ArrayList<Student> list; //instance variable
/**
* Constructor
*/
public StudentList(){
list = new ArrayList<Student>();
}
/**
* a method to print off all ArrayList elements
*/
public void printList(){
System.out.println("--Begin--");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("--End--");
}
/**
* A method to add a student to the list
*
*@param The student
*/
public void addToList(Student s){
list.add(s);
System.out.println("--Begin--");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) +"has been addded to the list");
}
System.out.println("--End--");
}
/**
* A method to remove a student from the list
*
*@param The student
*/
public void removeFromList(Student s){
list.remove(s);
System.out.println("--Begin--");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) +"has been removed from the list");
}
System.out.println("--End--");
}
/**
* A main method to test
*/
public static void main(String[] args) {
// Create an instance of the class
StudentList studentList = new StudentList();
//create 3 student objects
Student s1 = new Student("John Smith", "js@qmul.ac.uk", 2008);
Student s2 = new Student("Tom Will", "tw@qmul.ac.uk", 2007);
Student s3 = new Student("Cameron Young","Cammyoung@live.co.uk",2018);
//add the three students to the list
studentList.addToList(s1);
studentList.addToList(s2);
studentList.addToList(s3);
// Print the list
studentList.printList();
// Remove the student "Tom Will"
studentList.removeFromList(s2);
// Print the list again
studentList.printList();
}
}
2 回答
在addToList和removeFromList中,您可以打印所有学生 . 您可以删除循环并仅使用参数 . 并使用getName()仅打印名称
每次添加或删除用户时都会打印整个列表 . 我认为你的意思是“混乱” .
这是你的
addToList
方法应该是这样的: