0
public class ArrListPoly {
private int k;
private int[] arr;

public Object peek(int k) {
    return arr[k];
}

public int getHighestDegree() {
    return k;
}

public void setPoly(int k, int[] arr) {
    this.k = k;
    this.arr = arr;
}

public ArrListPoly sumPoly(ArrListPoly p1, ArrListPoly p2) {
    ArrListPoly p3 = new ArrListPoly();
    p3.arr = new int[p1.arr.length];
    for (int i = p1.arr.length - 3; i >= 0; i--)
        p3.arr[i] = p1.arr[i] + p2.arr[i];
    return p3;
}
}
public class ArrListPolyTest {

public static void main(String[] args) {
    ArrListPoly p1 = new ArrListPoly();
    int[] poly1 = { 9, 0, -3, 0, 5 };
    int p1highestDegree = poly1.length - 1;
    p1.setPoly(p1highestDegree, poly1);
    printPolyEq(p1, 1);

    ArrListPoly p2 = new ArrListPoly();
    int[] poly2 = { 2, 0, 4 };
    int p2highestDegree = poly2.length - 1;
    p2.setPoly(p2highestDegree, poly2);
    printPolyEq(p2, 3);

    ArrListPoly p3 = p1.sumPoly(p1, p2);
    int[] poly3 = new int[5];
    int p3highestDegree = poly3.length - 1;
    printPolyEq(p3, 1);
}

public static void printPolyEq(ArrListPoly p, int nTabs) {
    for (int i = 0; i < nTabs; i++)
        System.out.printf("\t");
    for (int i = p.getHighestDegree(); i >= 0; i--)
        System.out.printf("%+d x%d\t", p.peek(i), i);
    System.out.println();
}
}

I'd like to create two arrays to form a polynomial and add these two expressions to the result. I have completed printing the two polynomials, but the result is only one digit.

    +5 x4   +0 x3   -3 x2   +0 x1   +9 x0   
                    +4 x2   +0 x1   +2 x0   
                                    +11 x0  

↑like this.

I'd like to print out the sumPoly method by the 4th Exponent, so please advise me how to modify the sumPoly method.

ORing
  • 59
  • 5
  • 1
    "*How to increase the length of the array?*" - We cannot change the length of an array once it is created. We would have to create a new (larger) array and copy the old array's content. – Turing85 Apr 02 '21 at 15:03
  • Or use an `ArrayList`, an array-like collection that can dynamically change size when needed – Hovercraft Full Of Eels Apr 02 '21 at 15:05

0 Answers0