Q. Write a method add(PolyTerm): Two PolyTerm
objects can be added if and only if they have the same exponent. If
the calling object can be added to the parameter object, return
their sum, otherwise (if they can't be added), return null. For
example 2x^3 + -7.3x^3 = -5.3x^3 while 2x^3 + 8x^2 should return
null.
(It's on JAVA)
The JUnit Test for this question is:
public class PolyTermTest {
public static int score = 0;
public static String result = "";
public static String currentMethodName = null;
ArrayList<String> methodsPassed = new
ArrayList<String>();
PolyTerm t1, t2, t3, t4;
@BeforeEach
public void setUp() throws Exception {
currentMethodName = null;
t1 = new PolyTerm(1, 1); //x
t2 = new PolyTerm(2.4, 3);
//2.4x^3
t3 = new PolyTerm(-1.5, 0);
//-1.5
t4 = new PolyTerm(3.6, -2);
//3.6x^-2
}
@Test @Order(7) @Graded(marks=8,
description="add(PolyTerm)")
public void testAdd() {
assertNull(t1.add(t2));
assertNull(t1.add(t3));
assertNull(t1.add(t4));
assertNull(t2.add(t3));
assertNull(t2.add(t4));
assertNull(t3.add(t4));
PolyTerm t5 = new PolyTerm(1.1,
-2);
assertNotNull(t4.add(t5));
assertEquals(4.7,
t4.add(t5).coefficient, 0.001);
assertEquals(-2,
t4.add(t5).exponent);
currentMethodName = new
Throwable().getStackTrace()[0].getMethodName();
}
// Assuming Polyterm contains fields coefficient and
exponent
public PolyTerm add(PolyTerm p)
{
// exponents are same
if(exponent == p.exponent)
// create a new PolyTerm where
coefficient = sum of this and p's coefficient and exponent = this's
exponent
return new
PolyTerm(coefficient+p.coefficient, exponent); // Assuming PolyTerm
contains a constructor that takes as inputs coefficient as first
argument and exponent as secon argument
else // exponents are not same
return null;
}
Get Answers For Free
Most questions answered within 1 hours.