-6

I don't know what is the problem with this code.

public Polynomial negate(){

    int i;

    for(i = 0; i<this.coefficients.length;i++){

        this.coefficients[i] = -this.coefficients[i];
    }

    return this;

}

Polynomial is the name of the class and coefficients[] is an array of the coefficients. This method is supposed to return the array with all its values negated, but instead it returns some weird directions like [D@5afaa824

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
  • Show your full code. And just for the record, what you are doing is questionable, at best. What if two concurrent threads try and call your method simultaneously on the same instance? – fge Mar 01 '16 at 23:15
  • Please give the code showing how you are calling this. – Andy Turner Mar 01 '16 at 23:15
  • 1
    Could you provide additional information about what code is using negate? To me, that sounds like you're trying to do a System.print(somePolynomial). The code itself looks to me like it should be working - return this is just fine in Java. – Sessamekesh Mar 01 '16 at 23:16
  • You need to use `Arrays.toString(array)` to print the contents of an array in a sane manner. – Peter Lawrey Mar 01 '16 at 23:17
  • @fge how is that dubious? Most of the classes don't need to be thread-safe. I would certaily not make a Polynomial class thread-safe by default. Thread-safety is irrelevant to the question. – JB Nizet Mar 01 '16 at 23:17
  • From `[D@5afaa824` I can tell that `coefficients` is an array of doubles. Don't just do a `System.out.println(obj.coefficients)` because `coefficients` is an array. – callyalater Mar 01 '16 at 23:19

2 Answers2

0

That depends on the rest of your code. By itself, the code you wrote looks valid. Without seeing anything else, I'd imagine the problem is either:

1) The calling code is expecting an array, and instead is receiving a Polynomial

To fix this, change the method to return an int[] as so:

public int[] negate(){
    int i;
    for(i = 0; i<this.coefficients.length;i++){
        this.coefficients[i] = -this.coefficients[i];
    }
    return this.coefficients;
}

2) The calling code is expecting a polynomial, but not using it correctly

If you have something like this:

System.out.print(myPolynomial.negate());

then you're going to have a bad time. Try replacing it with something like this:

myPolynomial.negate();
System.out.println(Arrays.toString(myPolynomial.coefficients));
Sessamekesh
  • 420
  • 1
  • 6
  • 10
-1

It is supposed do be called by this other method this way :

Polynomial test = new Polynomial(4);

// Give values

test.negate().evaluate(5)

This is the evaluate method:

public double evaluate(double x){

    double result = 0;

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

        result +=coefficients[i] * Math.pow(x,i);

    }

    return result;

}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243