I was asked to write a programthat merges two files that contain polynomials in
ID: 3616795 • Letter: I
Question
I was asked to write a programthat merges two files that contain polynomials in sorted order.When two sorted files are merged, the result will besorted
This program should containthree classes.The firstclass Project1 should contain the two methods describedbelow:
The second class should be aclass namedPolynomial. It should implement theComparableinterface. The polynomial shouldbe stored as an array of integers. The size of the array should beone more than the highest exponent. This class should contain thefollowing methods.
6x4 + 7x2 +3 > 20x3 + 8x2 + 10
7x4 + 7x2 + 3 > 6x4 +17x2 + 7x + 30
6x4 + 9x2 + 3 > 6x4 + 7x+9
Explanation / Answer
publicclass Polynomial implements Comparable { // classmethods public Polynomialinput(BufferedReader file) { return newPolynomial(file.nextLine()); } // instancefields privateint[] coefficients; publicPolynomial(String input) { Scanner chopper =new Scanner(input); int coefficient =chopper.nextInt(); int exponent =chopper.nextInt(); //set array size coefficients = new int[exponent+1]; coefficients[exponent]= coefficient; while(chopper.hasNextInt()) { coefficient = chopper.nextInt(); exponent = chopper.nextInt(); coefficients[exponent] =coefficient; } } // accessors publicString toString() { String output =""; for(int i= coefficients.length-1; i >=0; i--) { if(coefficients[i]!=0) { // * add coefficient tooutput: be careful of + and - signs } } return output; } publicint compareTo(Polynomial rhs) { //check degree if(coefficients.length !=rhs.coefficients.length) { return rhs.coefficients.length- coefficients.length; } //else check coefficients for(int i= coefficients.length-1; i>=0; i--) { if(coefficients[i] !=rhs.coefficients[i]) { returnrhs.coefficients[i] -coefficients[i]; } } return 0; } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.