Reference no: EM1357715
Write a program that merges two files that contain polynomials. To merge two files, the input files must be in sorted order. The merge operation repetitively selects the smaller value from the two files. When two sorted files are merged, the result will be sorted.
This program should contain three classes. The first class Project1 should contain the two methods described below:
The main method, which calls the checkSorted method twice to verify that each of the input files is sorted in ascending order. It should catch the exception FileUnsorted if it is thrown, display an error message and terminate the program. Otherwise, it then performs the merge operation. The output is to be displayed on the screen.
A class method called checkSorted, which returns a BufferedReader object. The user should supply the name of the input file. The file should be read and it should be verified that the file is in ascending order. If it is not, the exception FileUnsorted should be thrown. Otherwise, after the file has been completely read, it should be closed and reopened to position it at the beginning of the file.
The second class should be a class named Polynomial. It should implement the Comparable interface. The polynomial should be stored as an array of integers. The size of the array should be one more than the highest exponent. This class should contain the following methods.
A constructor.
A class method named input that reads in a polynomial. The buffered reader for the file should be passed to this method as a parameter. The polynomials in the file will be stored as integer pairs that represent a coefficient and its corresponding exponent. For example, 5 3 4 1 8 0 represents the polynomial 5x3 + 4x + 8. They will always be written from the highest exponent to the lowest. Exponents with zero coefficients will be omitted.
A toString method that converts a polynomial to a string. The polynomial 5x3 + 4x + 8 should be converted to the following string "5x^3 + 4x + 8".
A method compareTo that compares two polynomials. The comparison should be similar to the Big-O comparison of methods. If the two polynomials have different highest order exponents the one with the highest exponent is the greatest. If their highest exponents are the same their coefficients are compared. If two polynomials have the same highest order exponent with the same coefficients the next highest exponent is examined. The following examples should help explain the ordering:
6x4 + 7x2 + 3 > 20x3 + 8x2 + 10
7x4 + 7x2 + 3 > 6x4 + 17x2 + 7x + 30
6x4 + 9x2 + 3 > 6x4 + 7x +9
The third class should be the exception FileUnsorted. It requires no methods or instance data.