Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Program designed to showcase how to search then remove an element from a generic array of objects in Java.
- * Assume 'Student' is defined.
- * @author Nick Adamou
- * @date 9/1/2019
- */
- public class Main {
- // Function to obtain a specific student's position in an array of students
- public static int search(Student[] students, String firstName, String lastName) {
- // Loop over every student in the array of students.
- for (int i = 0; i < students.length; i++) {
- // Get the current student at this position in the array.
- Student student = students[i];
- // Check if student is null
- if (student == null) {
- // If student is null, then continue.
- conttinue;
- }
- // Check if this student is the one we are looking for.
- if (student.getFirstName().equalsIgnoreCase(firstName) &&
- student.getlastName().equalsIgnoreCase(lastName)) {
- // If it is the student we are looking for, return it's position in the array.
- return i;
- }
- }
- // If the student could not be found, return -1.
- return -1;
- }
- // Function used to remove a student from an array of students.
- public static Student removeStudent(Student[] students, firstName, lastName) {
- // Indicate to the user that we are removing a student.
- System.out.printf("Removing student (%s, %s)", firstName, lastName);
- // Search for the student in the array and get its position in the array.
- int index = search(students, firstName, lastName);
- // Store a blank version of the targetted student
- Student student = new Student()
- // Check if the student was found.
- if (index != -1) {
- // Indicate that the student was found.
- System.out.printf("FOUND Student (%s, %s) @ students[%d]", firstName, lastName, index);
- // Store the student we want to remove in 'student'.
- student = students[index]
- // If the student was found, start looping over the array of students starting at
- // that students position.
- for (int i = index; i < students.length; i++) {
- // Shift each student's position by 1.
- students[i] = students[i + 1];
- }
- // Decrease the index by 1. (Assume 'index' is defined by your class).
- this.index--;
- // Display the resulting array of students.
- for (int i = 0; i < students.length; i++) {
- // Store the student at this index.
- Student student = students[i];
- // Only display non-null students.
- if (student != null) {
- System.out.println(students[i]);
- }
- }
- } else {
- // Indicate that the student was not found.
- System.out.printf("COULD NOT FIND Student (%s, %s)", firstName, lastName);
- }
- // Return the resulting array of students.
- return student;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment