ArrayList和java的方法

时间:2013-10-03 03:37:14

标签: java arraylist

我一直在努力工作几个小时,所以我希望有人可以帮助我。我必须创建一个学生的arraylist并执行以下命令。添加,查找和删除学生。无论如何我的添加,查找功能工作正常,但当我尝试删除学生时,它会导致错误的学生!我不知道该做什么感觉就像我已经尝试了一切。

public void addStudent(String studentName, long studentID, String address) {
    Student newStudent = new Student ( studentName,  studentID, address);
    collegeList.add(newStudent);
}

public static  void deleteStudent() {
    Scanner input=new Scanner(System.in);
    System.out.print("Enter student ID");
    long studentNumber=input.nextLong();

    if(directory.isValidID(studentNumber) && directory. withinRange(studentNumber)) {
        System.out.print("Deleting Student");
        System.out.print(directory.findStudent(studentNumber));
        System.out.print("please confirm with y/n");
        Scanner myans=new Scanner(System.in);
        String confirmation=myans.next();

        if (confirmation.equals("y")) {
            directory.deleteStudent(studentNumber);
            System.out.print("student deleted");
        }

        if(confirmation.equals("n")) {
            System.exit(0);
        }
    }
}

/**
Searches for student based upon their student number
@param studentID unique student number for each student
@return students entire information
*/
public String findStudent(long studentID) { 
    String str;
    Student newStu;

    for (int i=0; i<collegeList.size(); i++ ) {
        newStu=collegeList.get(i);

        if(newStu.getStudentID()==studentID);

            return newStu.toString(); 
    }

    return null;
}

/**
Removing student from collegeList
@param studentID unique student number
@return none
*/
public void deleteStudent (long studentID) { 
    Student newStu;
    for (int i=0; i<collegeList.size(); i++ ) {
        newStu=collegeList.get(i);

        if (newStu.getStudentID()==studentID)
            collegeList.remove(i);
    }
}

2 个答案:

答案 0 :(得分:3)

如果我弄错了,请纠正我,但看起来你的比较是错误的。如果您发现得分较低,那么它会更新(与您想要的完全相反)。

highest>newStu.getQuizScore()

也许应该是

highest<newStu.getQuizScore()

您还需要迭代整个列表以找到最高分。现在您返回的第一个分数低于第一个分数,但这可能不正确。我会做这样的事情:

public Student findHighest () {

    Student highest;
    highest=collegeList.get(0);


    for (int i=1; i<collegeList.size(); i++ ) {

        Student newStu=collegeList.get(i);

        if (highest.getQuizScore()<newStu.getQuizScore()){
            highest=newStu;
        }

    }
    return highest;

}

对于我的回答有任何错误或问题,我很抱歉,我是Stack Overflow的新手。

干杯。

答案 1 :(得分:0)

您的Student类是否会覆盖hashCode()equals()方法?如果没有,它将无法与Java集合正常运行。

然后你应该能够做到这样的事情:

studentList.add(student);
...
int index = studentList.indexOf(student);
if (index != -1) return studentList.get(index);
...
studentList.remove(student);