Q:

How to delete an element from an array?

I'm trying to drop a student from course, and this is what i got so far..
public void dropStudent() {

 String id;     
 System.out.println(" Enter student ID " );     
 id = Keyboard.readString();

  for ( int i = 0; i <= students.length - 1; i++)   
  {
      if (id.equals(students[i].displayId()))
      {
          for (int j = i; j <= students.length - 1; j++)
          {
          students[i] = students[i+1];

          }

      }      
   } 
}

So the first loop is for each element of the array, the if statement is to check if the id entered match's a student's id from the array. the second "For" is to shift the elements back. when i try it, it does delete a specific student. but instead of shifting the elements back, it just copies the next element in both places. i tried to set the element to null, but it didn't work.
so any suggestions please ? i'm also not allowed to use array list or other things.

A:

You cannot alter the size of a Java array after instantiation.  If all that's needed is returning an array without the student id.  You'd want to create a new array with one fewer element, and iterate over the original array, copying all but the id you want to remove.
Normally, you'd want to use lists for this.  But given your constraints, that's how I'd tackle it.
Something like:
public String[] dropStudent(String delete, String[] students){
    int length=students.length-1, i=0;
    String[] remainingStudents= new String[length];

    for(String student: students){
        // catch the edge case where 'delete' is not found, and avoid the ArrayIndexOutOfBoundsException
        if(i==remainingStudents.length){
            return students;
        }
        // Add the any non-matching students to the final array.
        if(!student.equals(delete)){
            remainingStudents[i]=student;
            i++;
        }
    }
    return remainingStudents;
}

A:

use the variable "j" in your second loop
fix your logic so that "j+1" will not result to array index out of bounds

