0

I have a linked list containing all of my students(which are objects)

I want to be able to remove a student based on the id I pass in

Here is my code

import java.util.*;

public class Registry

{
    LinkedList<student> Students = new LinkedList<student>();
    Scanner myObj = new Scanner(System.in);

    public Registry() {
    }

    public void addStudents() {

        System.out.println("Add a new student");
        System.out.println("Enter ForeName");
        String foreName = myObj.nextLine();
        System.out.println("Enter SurName");
        String surName = myObj.nextLine();
        System.out.println("Enter Student ID");
        String studentID = myObj.nextLine();
        System.out.println("Enter Degree Scheme");
        String degreeScheme = myObj.nextLine();
        Students.add(new student(foreName, surName, studentID, degreeScheme));
    }

    public LinkedList<student> getStudents() {
        return Students;
    }

    public void deleteStudent() {
    System.out.println("Enter the ID of the student you want to remove");
    String studentID = myObj.nextLine();
    Students.remove(student)
    }
}

In the deleteStudent method I do not know how to locate the student with the id

I then presume I can just use .remove(student) to remove the student?

How can I locate the student with the id?

Many Thanks for your help

0

2 Answers 2

0

I think what you can do is iterate through the LinkedList to find a student with same studentID and remove that from the LinkedList.

for(Student student:getStudents()){
    if(student.studentID.equals(studentID)) students.remove(student);
 }
Sign up to request clarification or add additional context in comments.

Comments

0

We can use Collection::removeIf:

Students.removeIf(student -> Objects.equals(student.getId(), studentId));

Ideone demo

(The code snippet assumes a getId() method on Student and that the types of studentId and Student::getId are Comparable)

A remark on the code: In java, field names should be written in camleCase (LinkedList<student> Students ... -> LinkedList<student> students ...)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.