Ice Art
Ice Art

Reputation: 57

Java - Classes and Objects, Set isn't working?

I'm creating a QuarterResult class and basically I'm having trouble with the setResult method (this isn't the entire code, but the code that's necessary for my question).

public class QuarterResult {
    private double[] results;

    public QuarterResults() {
        results = new double[4];
    }

    /**
     * Set the results at index i to the result passed as the parameter
     * @param index (return if OOB)
     * @param result 
     */
    public void setResult(int index, double result) {
        if (index <= 0 || index >= results.length) {
            return;
        }
        else {
            for (int i = index; i < results.length; i++) {
            results[index] = result;
        }
    }
}

Test code:

myResult.setResult(0, 25.1);
assertEquals(25.1, myResult.getMark(0), 0.01);

ERROR: java.lang.AssertionError: expected:<25.1> but was:<0.0>


Now when I changed the code as the suggestions said. I'm now getting an exception:

java.lang.NullPointerException
at xxxx.QuarterResult.setResult(QuarterResult.java:25)

Which is the

if (index <= 0 || index >= results.length) {

line.

Can someone explain why this doesn't work, it seemed to work with the similar example in the textbook but just doesn't work with my code.

Upvotes: 0

Views: 91

Answers (1)

Thomas
Thomas

Reputation: 88707

if(index<= 0 ... - you're passing 0 so nothing happens. I guess you mean if( index < 0 ... instead.

Besides that, I'd not just end the method in this case but throw an exception, e.g. IllegalArgumentException, otherwise you might miss wrong parameters (as you obviously did).

Also look at this code:

for (int i = index; i < results.length; i++) {
    results[index] = result;
}

Is the loop really necessary? (Hint: no)

From your comment: "still unsure what's wrong with my answer"

I assume you mean why you get the assertation error. Due to the error in your code results[0] was never set and thus still has the value it was initialized with, which is 0.0 for double variables or elements of double[] arrays.

Upvotes: 5

Related Questions