【发布时间】:2019-05-10 20:23:47
【问题描述】:
我正在尝试获得与此类似的输出 -
John Smith 已添加到学生列表中
Tom Will 已添加到学生列表中
您的姓名已添加到学生列表中
--开始--
姓名:John Smith 电子邮件:js@qmul.ac.uk 年份:2008
姓名:Tom Will 电子邮件:tw@qmul.ac.uk 年份:2007
姓名:您的姓名电子邮件:您的电子邮件年份:您的年份
--结束--
Tom Will 已从学生列表中删除
--开始--
姓名:John Smith 电子邮件:js@qmul.ac.uk 年份:2008
姓名:您的姓名电子邮件:您的电子邮件年份:您的年份
--结束--
但它打印的内容很混乱。我的代码哪里出错了?
代表学生的班级:
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();
}
}
【问题讨论】:
-
你能说明它是如何“糊涂”的吗?
-
看来你需要学习使用调试器了。请帮助自己一些complementary debugging techniques。如果您之后仍有问题,请随时回来提出更具体的问题。
标签: java arrays arraylist methods