Sum of the quadratic sum
It's been three years since I made java, so I'm pretty rusty.
Problem: Quadratic equation is (x ^ 2) + b (x) + c (a, b, c are coefficients)
public static Quadratic sum(Quadratic q1, Quadratic q2)
Postcondition: The return value is a quadratic expression obtained by adding q1 and q2. For example, the C factor of the return value is the sum of the q1 c factor and the q2 factor.
I am stuck trying to remember how to add these squares and then return their sum. Here's what I have. I'm pretty sure I've gone a bit and made a lot of changes, but I'm looking for a little guidance.
public static Quadratic sum(Quadratic q1, Quadratic q2){
int newA =(q1.a + q2.a);
int newB =(q1.b + q2.b);
int newC =(q1.c + q2.c);
return;
}
source to share
You must return a new object Quadratic
with the individual odds sums. There are several ways to do this. Here is one of them:
public static Quadratic sum(Quadratic q1, Quadratic q2) {
int newA =(q1.a + q2.a);
int newB =(q1.b + q2.b);
int newC =(q1.c + q2.c);
return new Quadratic(newA, newB, newC);
}
To do this, you need to have the following constructor in the class Quadratic
:
Quadratic(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
So your class will look something like this:
class Quadratic {
int a;
int b;
int c;
Quadratic(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
If you don't want to add a new constructor, you can assign values ββseparately before returning a new one Quadratic
. This would be another way to achieve the same:
public static Quadratic sum(Quadratic q1, Quadratic q2){
Quadratic result = new Quadratic();
result.a =(q1.a + q2.a);
result.b =(q1.b + q2.b);
result.c =(q1.c + q2.c);
return result;
}
EDIT:
Based on your comment, if you want to use your method setQuadratic()
, you need to put it in a class Quadratic
. Like this:
class Quadratic {
int a;
int b;
int c;
void setQuadratic(int newA, int newB, int newC) {
a = newA;
b = newB;
c = newC;
}
}
// ... rest of your code
public static Quadratic sum(Quadratic q1, Quadratic q2){
Quadratic result = new Quadratic();
int newA =(q1.a + q2.a);
int newB =(q1.b + q2.b);
int newC =(q1.c + q2.c);
result.setQuadratic(newA, newB, newC);
return result;
}
However, having a constructor makes instantiation and initialization in one step (i.e. new Quadratic(newA, newB, newC)
) easier / cleaner code than two methods: a constructor to instantiate and a set () method to initialize, which is what you currently have.
I would suggest moving on to the first solution above.
source to share