0

Ok well I posted a question with a small portion of my code. I realized that it would be easier for people to answer if they could see the entire code. I get nullpointerException when I run the program. I am not allowed to use .replace .copy .remove with regards to arrays. Im not sure why but thats what my teacher wants.

Class Grades:

public class Grades {

    // Fields

    private float[] listOfGrades;
    private int numOfScores;

    //
    // Constructor
    public Grades() {
        float[] listOfGrades = new float[0];
    }

    public Grades(float[] g) {

        for (int i = 0; i < g.length; i++) {
            if (g[i] >= 0 && g[i] <= 100) {
                listOfGrades[i] = g[i];

            }
        }

    }

    //
    // AccessorMethods
    public int getNumberOfScores() {
        try {
            int numOfScores = 0;
            for (int i = 0; i < listOfGrades.length; i++) {
                numOfScores++;

            }
        } catch (Exception e) {

        }

        return numOfScores;
    }

    public float[] getCopyOfListOfGrades() {
        float[] listOfGradesCopy = new float[listOfGrades.length];

        for (int i = 0; i < listOfGrades.length; i++) {

            listOfGrades[i] = listOfGradesCopy[i];
        }
        return listOfGradesCopy = listOfGrades;

    }

    public float getFirstGrade() {

        return listOfGrades[0];

    }

    public float findMax() {

        float largest = listOfGrades[0];

        for (int i = 0; i < listOfGrades.length; i++) {
            if (listOfGrades[i] > largest) {
                largest = listOfGrades[i];
            }
        }
        return largest;
    }

    public float findMin() {

        float largest = listOfGrades[0];

        for (int i = 0; i < listOfGrades.length; i++) {
            if (listOfGrades[i] < largest && listOfGrades[i] != 0) {
                largest = listOfGrades[i];
            }
        }
        return largest;
    }

    public float calculateAverage() {
        float avg = 0;
        for (int i = 0; i < listOfGrades.length; i++) {
            if (listOfGrades[i] != 0) {
                avg += listOfGrades[i];
            }
        }
        return avg / 100;

    }

    public void addGrade(float g) {
        if (g >= 0 && g <= 100) {
            float[] newListOfGrades = new float[listOfGrades.length + 1];

            for (int i = 0; i < newListOfGrades.length; i++) {

                newListOfGrades[i] = listOfGrades[i];
                if (listOfGrades.length == i) {

                    listOfGrades[i] = g;
                }
            }

        } else {
            System.out.println("Sorry number not in range");
        }
    }

    public Grades deleteGrade(float g) {

        float[] result = new float[listOfGrades.length - 1];
        int index = 0;
        for (int i = 0; i < listOfGrades.length; i++) {
            if (listOfGrades[i] == g) {

                result[index] = listOfGrades[i];
                index++;
            }
        }
        Grades newGrade = new Grades(result);

        return newGrade;

    }

}

Class GradesTest:

/* Grades Client */
public class GradesTest {
    public static void main(String[] args) {

        // Test the default constructor.
        Grades emptyScores = new Grades();

        if (emptyScores.getNumberOfScores() != 0)
            throw new Error("default constructor failed");

        // Now test the parameterized Constructor
        float[] a1 = { 70, 60, 80, 90, 100 };
        Grades allQuizScores = new Grades(a1);

        if (allQuizScores.getNumberOfScores() != 5)
            throw new Error("Parameterized constructor failed");

        float[] a = { 70, -34, 108, 60, 80, -8.9f, 90, 100 };
        allQuizScores = new Grades(a);

        // Now test getNumberOfScores
        if (allQuizScores.getNumberOfScores() != 5)
            throw new Error("Parameterized constructor failed with invalid grades");

        if (emptyScores.getFirstGrade() != -1)
            throw new Error("getFirstGrade failed to handle empty arrays");

        a[0] = -100;

        // Now check that allQuizScores didn't change
        if (allQuizScores.getFirstGrade() == -100)
            throw new Error("Constructor failed to make a copy of array");

        // Check getCopyOfListOfGradeds
        a = emptyScores.getCopyOfListOfGrades();
        if (a.length != 0)
            throw new Error("getCopyOfListOfGrades failed on empty array");

        a = allQuizScores.getCopyOfListOfGrades();
        a[0] = -100;
        if (allQuizScores.getFirstGrade() == -100)
            throw new Error("getCopyOfListOfGrades failed to make a copy of array");

        // Now check that min,max, and average are correct
        if (allQuizScores.findMin() != 60)
            throw new Error("failed to find minimum value");

        if (emptyScores.findMin() != -1)
            throw new Error("findMin failed to handle case of empty array");

        if (allQuizScores.findMax() != 100)
            throw new Error("failed to find maximum value");

        if (emptyScores.findMax() != -1)
            throw new Error("findMax failed to handle case of empty array");

        if (allQuizScores.calculateAverage() != 80)
            throw new Error("failed to find average value");

        if (emptyScores.calculateAverage() != -1)
            throw new Error("findAverage failed to handle case of empty array");

        // Testing addGrade
        emptyScores.addGrade(10);
        if (emptyScores.findMin() != 10 || emptyScores.getNumberOfScores() != 1)
            throw new Error("addGrade fails on empty array");
        allQuizScores.addGrade(10);
        if (allQuizScores.findMin() != 10 || allQuizScores.getNumberOfScores() != 6)
            throw new Error("addGrade fails on non-empty array");
        allQuizScores.addGrade(-10);
        if (allQuizScores.findMin() == -10)
            throw new Error("addGrade fails for invalid grades");

        allQuizScores.addGrade(10);
        allQuizScores.addGrade(10);
        Grades newQuizScores = allQuizScores.deleteGrade(allQuizScores.findMin());
        if (newQuizScores.getNumberOfScores() != 7)
            throw new Error("deleteGrade failed for non-empty array");
        Grades emptyScores2 = emptyScores.deleteGrade(10);
        if (emptyScores2.getNumberOfScores() != 0)
            throw new Error("deleteGrade failed for single-item array");
        emptyScores2 = emptyScores.deleteGrade(10);
        if (emptyScores2.getNumberOfScores() != 0)
            throw new Error("deleteGrade failed for empty array");

        // Test equals
        if (emptyScores.equals(allQuizScores))
            throw new Error("Equals fails");
        if (newQuizScores.equals(allQuizScores))
            throw new Error("Equals fails");
        float[] b = { 70, 60, 80, 90, 100, 10, 10 };

        Grades gr = new Grades(b);
        System.out.println(gr.toString());
        System.out.println(newQuizScores.toString());
        if (!newQuizScores.equals(gr))
            throw new Error("equals fails for non-empty array");
        System.out.println(emptyScores.toString());
        Grades gr2 = new Grades();
        if (!emptyScores2.equals(gr2))
            throw new Error("equals fails for empty array");

        // test toString
        System.out.println("The grades without the minimum grade are:\n" + allQuizScores.toString());
        System.out.println("If you are happy with the formatting, you're done!");
    }
}
7
  • 1
    Why are you creating an array of float numbers with zero elements? float[] listOfGrades = new float[0]; Commented Nov 28, 2013 at 23:48
  • @Fadi Hanna AL-Kass My teacher wanted us to put in an empty array Commented Nov 28, 2013 at 23:49
  • 2
    Well there's a difference between an empty array and an array with no locations to hold values (i.e. array of size 0) Commented Nov 28, 2013 at 23:50
  • Adding onto what Fadi said, arrays are initialized with a defined length so new float[0]; creates a float array with zero elements, where new float[2]; would create a blank float array with 2 empty elements. Commented Nov 28, 2013 at 23:54
  • Zero length arrays are perfectly valid code though. A good thing about them is, for example, that you can iterate over them like any old array. Quite a few use-cases for zero length arrays exist. Commented Nov 28, 2013 at 23:59

1 Answer 1

0

Your constructor with parameters does not take into account the internal array is initialized with zero length.

You'd have to add this line at the top:

listofGrades = new float[g.length];

Without this, assigning the contents of g into listofGrades fails with NPE.

public Grades(float [] g){
        listOfGrades = new float[g.length];
        for(int i = 0; i < g.length; i++){
            if(g[i] >=0 && g[i] <=100){
                 listOfGrades[i] = g[i];

        }
    }   

}

If you do work with zero length arrays, you need to keep in mind the fact that they might be still zero length at the time you try to access them, and react accordingly, for example in your method:

public float getFirstGrade(){

    return listOfGrades[0];

}

If you call this immediately after you constructed the object with the default constructor, it will throw a NullPointerException as well.

There are more oddities in your code, e.g. this:

public int getNumberOfScores(){
    try{
  int numOfScores = 0;
    for(int i = 0; i < listOfGrades.length;i++){
        numOfScores++;

    }
    }catch(Exception e){


    }

    return numOfScores;
}

You could write this simply as:

public int getNumberOfScores(){
    return listOfGrades.length;
}

This would work with a zero length array, as in this case length is zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.