?
Solved

remove an item from string array...

Posted on 2011-10-20
17
Medium Priority
?
211 Views
Last Modified: 2013-11-23
           students.remove(student);

This line (61) has an error.

Question: What is the correct syntax?

Thank you.
public class TestCourse{
    public static void main(String[] args){
        Course2 course1=new Course2("Data Structure");
        Course2 course2=new Course2("Database Systems");
        
        course1.addStudent("Peter");
        course1.addStudent("Brian");
        course1.addStudent("Anne");
        course1.addStudent("Mike");

        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 Course2{
    private String courseName;
    private String[] students=new String[100];
    private int numberOfStudents;
    
    public Course2(String courseName){
        this.courseName=courseName;
    }
    
    public void addStudent(String student){
        if (numberOfStudents>=3){
            System.out.println("Class is full, cannot add: "+student);
        }else{
            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
  • 11
  • 6
17 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 37004014
You can't remove from array
you can only assign element to null
then you can write a program to compreess array
after thet

Rather use ArrayList isnsteda of arrays

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37004023
You can create another array and copy all elemnts but this one, but you cannot simply remove from array - the sapce was already allocated
and I don't think you can reduce it. Only create new one.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37004026
arrays are really inconvenient - in most practical cases you want to use ArrayList instead.
Maybe only such things which will never change zsize, like  fields on the chessboard are good for array
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 47

Accepted Solution

by:
for_yan earned 1000 total points
ID: 37004034

I guess this would be the way to remove the last element:

students1 = new String[students.length-1];
for(int j=0; j<students.length-1; j++) students1[j] = students[j];
students = students1;

 
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 37004035
ok, I will try it and if I had follow up questions I will ask later.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37004038
Sure, you are always welcome.
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 37004112
I have a solution. If any improvement you see please let me know.
public class TestCourse{
    public static void main(String[] args){
        Course2 course1=new Course2("Data Structure");
        Course2 course2=new Course2("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 Course2{
    private String courseName;
    private String[] students=new String[100];
    private String[] students2=new String[100];//***************************
    private int numberOfStudents;
    
    public Course2(String courseName){
        this.courseName=courseName;
    }
    
    public void addStudent(String student){
        if (numberOfStudents>=3){
            System.out.println("Class is full, cannot add: "+student);
        }else{
            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{
            remove(student);//***************************
            numberOfStudents--;
        }
    }
    
    int j=0; //*************************************
    private void remove(String student){
        for(int i=0; i<students.length;i++){
            if(students[i]!=student){
                students2[j]=students[i];
                j++;
            }
        }
        students=students2;
    } //*****************************
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37004129
One thing you don't want to have stidents2 the same size as students1 - it will be a problem if you use student.length somehwre
another thing is taht you should never do this if( students[i]!=student){
as student[i] is a string - youi can use only equals
other than that I think, should be OK.

Open in new window


So, the bottomline - thsi is one of the big reasons that you don't want to deal wuith arrays
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 37004575
if( students(i)!=student){

works but

equals()

didn't work.

Maybe I didn't apply correctly. Here is the message:

run:
Class is full, cannot add: Mike
Exception in thread "main" java.lang.NullPointerException
      at Course2.remove(TestCourse.java:73)
      at Course2.dropStudent(TestCourse.java:64)
      at TestCourse.main(TestCourse.java:11)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 37004577
code tried...
public class TestCourse{
    public static void main(String[] args){
        Course2 course1=new Course2("Data Structure");
        Course2 course2=new Course2("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 Course2{
    private String courseName;
    private String[] students=new String[100];
    private String[] students2=new String[100];//***************************
    private int numberOfStudents;
    
    public Course2(String courseName){
        this.courseName=courseName;
    }
    
    public void addStudent(String student){
        if (numberOfStudents>=3){
            System.out.println("Class is full, cannot add: "+student);
        }else{
            students[numberOfStudents]=student;
            numberOfStudents++;
        }
    }
    
    public String[] getStudent(){
        return students;
    }
    
    public int getNumberOfStudents(){
        return numberOfStudents;
    }    
    
    public String getCourseName(){
        return courseName;
    }
    
    public void dropStudent(String student){
        if (numberOfStudents<=0){
            System.out.println("There is no one to drop.");
        }else{
            remove(student);//***************************
            numberOfStudents--;
        }
    }
    
    int j=0; //*************************************
    private void remove(String student){
        for(int i=0; i<students.length;i++){
//            if(students[i]!=student){
            if(students[i].equals(student)){
                students2[j]=students[i];
                j++;
            }
        }
        students=students2;
    } //*****************************
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37004610
Forget about  != for strings - and never use it - it is wrong and will fail sooner or later.

You used equals incorrectly, I think you should check is it is not null upfront,
because student1.equals(student2) will through null pointer if student is null

this is more or less how it should work:
still with the caveat that we assum that students to be removed is not null
and we know that there is one and only one student equal to that  wwhom  we need to remove.

String [] removeStudent(String [] student1, student) {
String [] student2 = new String[student1.length - 1];

int j=0;
for(String s : student1) {
if(student.equals(s)) continue;
student2[j] = s;
j++;

}

return student2;
}

Open in new window


Just never use these arrays - it is simply pain.


0
 
LVL 47

Expert Comment

by:for_yan
ID: 37004611
correction:
still with the caveat that we assume that the student to be removed is not null
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37004612
One more correction:
because student1.equals(student2) will throw null pointer if student1 is null
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37004617
if(students[i].equals(student))

Open in new window

will throw execption when you reach those elements which are null in your array

you should rather do

if(student.equasl(students[i])

Open in new window


You can check if (student != null) in the very beginning and return mmediately if student which you want to delete is null
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 37004638
I have to still go through your latest notes. But for now, after reading your not "make sure it is not null...", I tired the following and it runs ok using equal()
if(!(""+students[i]).equals(student)){

Open in new window

0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 37004650
Thank you for your good techniques. I also tried...
if(!(""+students[i]).equals(""+student)){

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37004651
if(!(""+students[i]).equals(student)){ <--yes this should probably be OK, as evene when students[i] is null ""+students[i] is not.
but if you reverse student.equals(students[i]) it should not throw null pointer - you just cannot invoke any methods on null,
but null can be argument of a method

Open in new window

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

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month16 days, 11 hours left to enroll

862 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