简体   繁体   中英

Replacing an item in an Object array with null (java)

I'm starting to learn object orientation in my course and we have an object class called students . An object of the students class stores the instance variables: studentName , studentNumber , and studentGPA . I have a boolean method in my object class that determines whether the student is a failing student or not (the student is failing if their GPA is > 2.0) and then I have a method in my worker class that is supposed to accept the array of students objects, and then if the student is failing, it replaces that object with "null".

My problem is that I'm having a hard time replacing the students objects with null, since java keeps throwing me or some such. Here's what I've tried:

public static void removeFailingStudents(Student[] students)
 {
  int count;

  for (count=0; count<students.length; count++)
  {
    if(students[count].isFailing())
    {
      students[count] = null;
    } 
  }
 }

and

public static void removeFailingStudents(Student[] students)
 {
  int count;

  for (count=0; count<students.length; count++)
  {
    if(students[count].isFailing())
    {
      students[count] = "null";
    } 
  }
 }

but when I compile/run these attempts it either throws me an exception or it yells at me because it is not of the type Student . How do I set an item in an array of objects to null?? Thanks for the help!

Here's my full code:

public class L2Q1
{
 public static void main(String[] parms)
 {
  process();

  System.out.println("\nEnd of processing.");
 }

 public static void process()
 {
  Student[] students;
  Student[] newStudents;

  students = getStudents();
  printStudents(students);
  printAverageGPA(students);
  printHonourStudents(students);
  removeFailingStudents(students);
  printStudents(students);
  newStudents = compactStudents(students);
  printStudents(students);
  printStudents(newStudents);
 }

 public static void printStudents(Student[] students)
 {
  int count;

  System.out.println("Students:");
  for (count=0; count<students.length; count++)
  {
    System.out.println(students[count].toString());
  }
  System.out.println();
 }

 public static void printAverageGPA(Student[] students)
 {
  double sumGPA;
  int count;

  sumGPA = 0;
  for (count=0; count<students.length; count++)
  {
    sumGPA += students[count].getGPA();  
  }
  double average = sumGPA / count;
  System.out.println("The average GPA is " + average);
  System.out.println();
 }

 public static void printHonourStudents(Student[] students)
 {
  int count;

  System.out.println("Honour students:");
  for (count=0; count<students.length; count++)
  {
    if(students[count].isHonourStudent())
    {
      System.out.println(students[count].toString());
    }
  }
  System.out.println();
 }

 public static void removeFailingStudents(Student[] students)
 {
  int count;

  for (count=0; count<students.length; count++)
  {
    if(students[count].isFailing())
    {
      students[count] = null;
    } 
  }
 }

 public static Student[] compactStudents(Student[] students)
 {
  Student[] newStudents;
  int count1;
  int count2;

  System.out.println("Compacting failing students.");
  System.out.println();
  count1 = 0;
  for (count2=0; count2<students.length; count2++)
  {

  }

  newStudents = new Student[0];
  return newStudents;
 }

 public static Student[] getStudents()
 {
  Student[] students = new Student[]
  {
   new Student(7654321, "Lara Zhivago", 3.75),
   new Student(7654322, "Betty Brown", 1.9),
   new Student(7654323, "Chris Cross", 0.5),
   new Student(7654324, "Dr. Dre", 4.0),
   new Student(7654325, "Joe Cool", 2.0)
  };

  return students;
 }
}

/******************************************************************/
/******************************************************************/

class Student
{
  private int number;
  private String name;
  private double gpa;

  public Student(int snum, String sname, double sgpa)
  {
    this.number = snum;
    this.name = sname;
    this.gpa = sgpa;

  }

  public double getGPA()
  {
    return gpa;
  }

  public boolean isHonourStudent()
  {
    boolean isHonourStudent = false;
    if(getGPA() >= 3.5)
    {
      isHonourStudent = true;
    }
    return isHonourStudent;
  }

  public boolean isFailing()
  {
    boolean isFailing = false;
    if(getGPA() < 2.0)
    {
      isFailing = true;
    }
    return isFailing;
  }

  public String toString()
  {
    return  number + " " + name + " " + gpa;
  }
}

Here's the exception message:

java.lang.NullPointerException
    at L2Q1.printStudents(L2Q1.java:41)
    at L2Q1.process(L2Q1.java:28)
    at L2Q1.main(L2Q1.java:13)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

This happens because you've already removed some of the students, turning them from Student to null . You're trying to call toString() on one of the non-existing students that are null .

I suggest you replace the array with ArrayList , from which you can actually remove elements. Alternatively, you can rebuild the array when you remove a student.

The Problem

You are making elements in your students array null. Then you try to use toString() but on a null element. This is how it looks like: null.toString() , obviously that is bad.


Solution Without ArrayList

On the comments people suggested an ArrayList . I am assuming this is homework and you are forced to use an array, therefore you should do this:

Keep track of the size of the array. Use that to determine how many real elements, non-null elements, you have on the list. Like this:

for(int i = 0; i < arraySize; i++)
{
    // Do something with the array here.
}

Make sure you declare arraySize as an instance variable .

private int arraySize = 0;

Remember you will need to increment arraySize for every new element and decrement it every time you null out an element.

Keep in mind that by the time your program finishes your array will have a trail of nulls at the end.


Hackish Solution

In the mean time you can do this to your printStudents() -- this is hackish and only a temporary fix.

public static void printStudents(Student[] students)
{   
    // Check if the array is null, good practice.   
    if(students == null)
        return;

    System.out.println("Students:");

    for (int i = 0; i < students.length; i++)
    {   
        // My hack: Check if element is null, if it is then skip it.
        if(students[i] == null)
            continue;

        System.out.println(students[i].toString());
    }

    System.out.println();
}

You are setting a Student object at an index to null , then later in a different method attempting to call toString() on a null object. Using List would help you work with this problem much more elegantly.

Without rewriting the whole code, here is how you could implement List instead:

public static void process() {
  List<Student> students = new ArrayList<Student>();
  List<Student> newStudents = new ArrayList<Student>();

...

Then when you loop through a List in all your different functions, you would use

  for (int count = 0; count < students.size(); count++) {
    //do stuff here
  }

If you want to remove a student from a list, use

students.remove(count);

To populate the list, use

Student student1 = new Student(7654321, "Lara Zhivago", 3.75);
students.add(student1);
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM