在没有Array.replace Array.copy的情况下使用和操作数组

时间:2013-11-28 23:44:26

标签: java arrays nullpointerexception

好吧,我发布了一小部分代码的问题。我意识到如果他们能够看到整个代码,人们会更容易回答。我运行程序时得到nullpointerException。关于数组,我不允许使用.replace .copy .remove。我不知道为什么,但这就是我的老师想要的。

班级成绩:

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!");
    }
}

1 个答案:

答案 0 :(得分:0)

带参数的构造函数没有考虑内部数组初始化为零长度。

您必须在顶部添加此行:

listofGrades = new float[g.length];

如果没有这个,将g的内容分配给listofGrades就会因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];

        }
    }   

}

如果你使用零长度数组,你需要记住,当你尝试访问它们时它们可能仍然是零长度,并做出相应的反应,例如在你的方法中:

public float getFirstGrade(){

    return listOfGrades[0];

}

如果在使用默认构造函数构造对象后立即调用它,它也会抛出NullPointerException。

您的代码中存在更多奇怪内容,例如:这样:

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

    }
    }catch(Exception e){


    }

    return numOfScores;
}

你可以简单地写成:

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

这适用于零长度数组,因为在这种情况下长度为零。