?
Solved

list.remove(name); doesn't work

Posted on 2011-10-30
5
Medium Priority
?
303 Views
Last Modified: 2012-05-12
In the method:

    public void dropStudent(String student){
        if (numberOfStudents<=0)
            System.out.println("There is no one to drop.");
        else
//            students.remove(student);
            numberOfStudents--;
    }  

For some reason, students.remove(student); doesn't work.

I want to supply student name to remove it it from students[] within the Course class. The existing method sort of works if the students are dropped in a reverse method.
public class TestNewCourse { // 
    public static void main(String[] args){
        Course course1=new Course("Data Structure");
        Course course2=new Course("Database Systems");
        
        course1.addStudent("Peter");
        course1.addStudent("Brian");
        course1.addStudent("Anne");
        course1.addStudent("Mike");
//
        course1.dropStudent("Brian");  //***************************
        
        course2.addStudent("Peter");
        course2.addStudent("Jack");
        
        System.out.println("Number of students in cours1: "+
            course1.getNumberOfStudents());
        String[] students=course1.getStudent();
        for(int i=0;i<course1.getNumberOfStudents();i++)
            System.out.println(students[i]+", ");
        
        System.out.println("");
//                
        System.out.println("Number of students in cours2: "+
            course2.getNumberOfStudents()+" students");      
    }
}

class Course{
    private String courseName;
    private String[] students=new String[2];
    private int numberOfStudents;
    
    public Course(String courseName){
        this.courseName=courseName;
    }
    
    public void addStudent(String student){
        
        if (numberOfStudents==students.length){
            String[] temp=new String[2*students.length];
            System.arraycopy(students, 0, temp, 0, numberOfStudents);
            students=temp;
        }       
        students[numberOfStudents]=student;
        numberOfStudents++;
    }
    
    public String[] getStudent(){
        return students;
    }
    
    public int getNumberOfStudents(){
        return numberOfStudents;
    }    
    
    public String[] getCourseName(){
        return students;
    }
    
    public void dropStudent(String student){
        if (numberOfStudents<=0)
            System.out.println("There is no one to drop.");
        else
//            students.remove(student);
            numberOfStudents--;
    }    
}

Open in new window

0
Comment
Question by:Mike Eghtebas
  • 3
  • 2
5 Comments
 
LVL 28

Accepted Solution

by:
dpearson earned 2000 total points
ID: 37053593
If you're storing the students in an array like this:

private String[] students=new String[2];

then when you want to remove something from the array, you need to shift the others down in the list.  E.g. say you remove student[3], you need to move all of the students > 3 down 1 in the list.

private int findStudent(String student) {
    for (int p = 0 ; p < students.length; p++) {
       if (students[p].equals(student))    // Consider equalsIgnoreCase here too perhaps
          return p ;
    }
    return -1 ;
}

public void dropStudent(String student) {
    int pos = findStudent(student) ;
   
    if (pos == -1) {
       System.err.println("Tried to drop student " + student + " who is not in the list") ;
       return ;
   }
 
    numberOfStudents-- ;

   // If removing the last student nothing to copy
   if (pos == students.length-1)
      return ;
 
   // Copy all of the elements down 1 (doing these params on the fly - might be a little off)
   System.arraycopy(students, pos+1, students, pos, students.length-pos-1);
}

This will work, but it's a fair bit of work.  What you might want to consider is instead switching to:

private ArrayList<Sting> students = new ArrayList<String>() ;

This list then has methods like add() and remove() that do exactly what you want and will manage the size of the list (growing and shrinking it as necessary).

If you're looking to learn more about arrays then it's fine to stick with String[].  But if you just want to manage a list of students, ArrayList will be much easier.

Doug
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 37053649
I will try this,

brb
private int findStudent(String student) {
    for (int p = 0 ; p < students.length; p++) {
       if (students[p].equals(student))    // Consider equalsIgnoreCase here too perhaps
          return p ;
    }
    return -1 ;
    }
    
    public void dropStudent(String student){
        int pos = findStudent(student);

        if (pos == -1) {
            System.err.println("Tried to drop student " + student + " who is not in the list") ;
        }else{
            String[] temp=new String[students.length];
            System.arraycopy(students, 0, temp, 0, pos-1);// copy list upto pos-1
            int trail=students.length-pos; // find number of items past the item at index = pos
            System.arraycopy(students, pos+1, temp, pos, trail); // copy the trailing portion
            students=temp; // new students array without the remove student name           
        }
            //        return ;
        numberOfStudents-- ;
   }

Open in new window

0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 37053665
this is a bit better but not quite correct...
public void dropStudent(String student){
        int pos = findStudent(student);

        if (pos == -1) {
            System.err.println("Tried to drop student " + student + " who is not in the list") ;
        }else{
            String[] temp=new String[students.length];
            System.arraycopy(students, 0, temp, 0, pos);// copy list upto pos-1
            int trail=students.length-pos; // find number of items past the item at index = pos
            System.arraycopy(students, pos, temp, pos, trail); // copy the trailing portion
            students=temp; // new students array without the remove student name           
        }
            //        return ;
        numberOfStudents-- ;
   }

Open in new window

0
 
LVL 34

Author Closing Comment

by:Mike Eghtebas
ID: 37053693
I hadn't read all of your comments.

Thank you.
0
 
LVL 28

Expert Comment

by:dpearson
ID: 37053861
If you're going to create a new list then this step:

String[] temp=new String[students.length];

should be:

String[] temp=new String[students.length-1];

because you will be dropping somebody from the list.  It will also help make sure you have the copy steps correct as copying the wrong number of elements will lead to an exception if you go past the end of the 'temp' list - which can easily happen if you get an "off by 1" error in the calculations.

Doug
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month14 days, 15 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question