Sie sind auf Seite 1von 12

Technical University of Cluj-Napoca Faculty of Automation and Computer Science Department of Computer Science 2nd Semester 20 !

-20 "

Programming Techniques ~Homework no. 1~

-1/12-

Student: Petrescu Serban Group: 30 !1

Contents:
# $%jectives &#######################################################################################! 2# 'ro%lem analysis &############################################################################" !# Desi(n &############################################################################################) !# # !#2# !#!# !#"# U*+ Dia(rams &#################################################################, Data Structures #####################################################################Class Desi(n and .elationships &########################################/ User 0nterface &################################################################# 0

"# 0mplementation and Testin( &########################################################## )# .esults &########################################################################################### ,# Conclusions &################################################################################## 2 -# 1i%lio(raphy &################################################################################# 2

-2/12-

1. "b#ecti$es
We must propose, design and implement a system for processing polynomials of one variable and integer coefficients. The program must implement a minimal number of operations which can be applied to the specified type of polynomials: addition subtraction multiplication derivation computation of the polynomials value at a given point

The application aims to be a calculator-li e !i.e. similar to Window"s #alculator.e$e program% application which allows the user to input any polynomial !of the specified type% or any operation between e$isting polynomials. &ecause of this intended behavior, several additional operations must be added to the problem itself: displaying the value of a polynomial parsing !reading from the user input% the value of a polynomial storing a polynomial deleting a polynomial

't results that the application must provide a way for the user to input commands in order to perform these operations. (lso, because the application will be able to store any amount of polynomials at a given time, a way for viewing the currently stored values must be created. (lso, most of the operations described in the list above, generate a result, which will have to be displayed in a designated place. )oreover, for simplicity, the application must provide a way for the user to directly use the result of a previous operation in further commands. 't results that the following functions must be added: displaying the currently stored values interpreting a command storing the result of the current operation displaying the result of a previous operation

&ecause a command interpreter was added to the layout of the problem, the program must also be able to detect wrong/faulty user input and provide pertinent warnings. ( short guideline must be presented to the user to describe the synta$ and all the possible commands and options supplied by the polynomial processor.

-*/12-

!. Prob%em ana%&sis
We must decide on a general way of solving the problem. The best way is to consider that each individual operation enumerated in the ob+ectives must be considered as a sub-problem. ,ome additional sub-problems appear !e.g. the internal representation of the polynomial% and the whole set of sub-problems must be arranged in an order such that, when se-uentially solving these sub-problems, we do not encounter a dependency to a not-yet-solved sub-problem !i.e. a problem hierarchy must be devised%. .irstly, we must decide how to design the internal representation of the polynomial, such that all the polynomial-related operations can be easily performed. 't is easily noted that a polynomial is actually a sum of terms !monomials%. Thus, we can conclude that a polynomial is actually a collection of independent terms. ( term consists of a degree !the power at which the variable "/" is raised% and a coefficient !a scalar value which is multiplied with the variable%. The problem statement describes the polynomials as having integer coefficients, so the terms will be designed with integer coefficients as well. 0ne can also observe that terms of the same degree can !and should% be merged in a single term, via the addition of the coefficients. ,o, the polynomial viewed as a collection of terms, can be classified even more e$clusively as being a collection of uni-ue terms !where the uni-ueness is based solely on the degree%, i.e. a polynomial can have at most one term of a given degree !if other terms of this degree "must" be added, they will be actually merged into the e$isting term%. 1sing the above-mentioned structure, all the polynomial operations presented in the ob+ectives can be viewed as operations between collections as follows: addition: can be viewed as a union between collections !collisions will be managed with merges as described in the paragraph above%2 subtraction: can also be seen as a union between collection, the only difference from the addition operation being that the second operand must have all it"s coefficients negated before performing the union2 multiplication: will be e$ecuted as a series of unions, multiplying one of the polynomials by each term of the other polynomial !i.e. adding the selected term"s degree to all degrees of the first polynomial and multiplying all the coefficients with the selected term"s coefficient%2 derivation: consists of removing the term with a null degree !if this term e$ists in the collection%, multiplying each term"s coefficient with it"s degree and decrementing the degree afterward. computation: results from summing the computation of each term. .or any given term, it"s value can be computed in a given point by raising the given value at a power e-ual to the term"s degree and multiplying the result with the coefficient.
-3/12-

,econdly, if we want the user to be able to store any number of polynomials using the application, a way for identifying each polynomial must be created. The simplest way that comes to mind is to associate a name !as in mathematics% to each polynomial. &asically each polynomial can be considered as a variable and the application as a set of such variables. &ecause each variable !polynomial% can be uni-uely identified , these set will contain uni-ue elements each one consisting of a name-polynomial pair !basically the name will be a key and the polynomial will be the value%. (l the related operations can be reduced to simple set operations !adding one element, removing one element, chec ing for e$istence, etc.%. The command interpreter can have many implementations. ( simple and fairly use one is the te$t command interpreter !+ust li e the shell, bash, cmd.e$e command interpreters%. .or simplicity, the application will e$pect e$actly one command per line and lin ing more commands between each other must be done by using the results from those operations and an additional operation to compute the final result. The result obtained in the last command must also be stored in some way. &ecause most of the operations return a polynomial !those which do not can not be used in aggregation with further operations anyway%, we will store this result in the polynomial set, lin ing it with a special, predefined name !a special symbol of sorts%. 'mplementing this feature this way we will automatically solve all sub-problems related to the "last result", as it will be treated and displayed as a regular polynomial. The only particularity will be that the user will not be able to delete this polynomial.

3. 'esign
1sing the ideas produced in the problem analysis phase, we must now design the classes, methods, properties and relationships which will completely capture all the re-uirements and goals described in the problem statement. .irst we will ma e a series of diagrams that depict the behavior of the whole system. !# # U*+ Dia(rams #4# #ards:

Term - ,tores the internal representation of a term - 5rovides a way to represent itself as a string - 5rovides a way to clone itself - 5rovides a way to merge itself with another term - 5rovides a way to evaluate itself in a given point
-6/12-

No colla%orators 2All other a((re(ated types are either primitives or of Term-type3

Polynomial - ,tores the internal representation of a polynomial - 5rovides a way to represent itself as a string - ,upports binary and unary polynomial operations - 5rovides a way to e$tract its value from a string Term 24 5ava predefined classes6 TreeSet7 Navi(a%leSet7 0terator3

Evaluator - ,tores and manages the polynomials created by the Term7 'olynomial user 24 5ava predefined classes6 - 'nterprets the commands submitted by the user *ap3 - ,tores and manages the results obtained

Graphical Interface - )anages the communication between the user and the evaluator 8valuator - 7isplays all the necessary information created by the 24 5ava predefined classes6 evaluator 5Frame7 5'anel7 etc3 - 5rovides a shot help te$t for command synta$ #lass 7iagram !public view%

-8/12-

1ser 'nterface .low 7iagram

!#2# Data Structures We will now analy9e each class and determine the way information should be stored internally. )ore e$plicitly, we will focus on selecting the data structure which best fits the characteristics of the data being stored. Term: all the data that needs to be stored and represented internally are the degree and the coefficient. The degree will be represented as an integer !any polynomial will have an integer-typed degree% and the coefficient will also be stored in an integer instance variable, because of the problem statement. 5olynomial: we have previously established that a polynomial is a collection of uni-uely identifiable terms. &ecause of this fact, and that this collection will need to be navigated in both directions, the best type of container will be a :avigable,et implemented as a Tree,et. :o other data should be stored, as any other information regarding the polynomial !degree, number of non-9ero terms, etc% can be easily retrieved from the Term collection itself.

-;/12-

<valuator: the data which is contained by this class is composed of: a collection of name-polynomial pairs and a message containing any errors provided in the commands issued. The message will be stored as a ,tring !as their comple$ity is small, we do not need e$tra fields such as severity levels% and the name-polynomial pair collection will be represented by a )ap implemented as a Tree)ap. (s previously stated, the management of results obtained from operation evaluation is inherently solved by treating the result as an ordinary polynomial with a special identifier. =raphical'nterface: all the of the logical application data is stored in the classes described above. This class has to store au$iliary data resulted from the graphical interface. Thus, it will have instance variables for all >.ames, >5anels, >Te$t.ields, etc that are used in the user interface. !#!# Class Desi(n and .elationships (ll fields !properties% of all classes were previously discussed. We are now interested in deciding what methods and constructors !both public and private% are needed for a smooth implementation of the application. 1. Term

pu%lic Term236 constructor2 creates a null term !the degree and coefficient are ?% pu%lic Term2int coefficient7 int de(ree3: constructor2 creates a term of a given coefficient and degree. pu%lic Term2Strin( to9en36 constructor2 parses a given string and builds a Term from it. private int parseCoefficient2Strin( s36 a private method which parses the coefficient out of a given string. private int parseDe(ree2Strin( s36 a private method which parses the degree out of a given string. private Strin( coefficientToStrin(2%oolean include'lus36 creates a ,tring which represents the current Term"s coefficient. ( plus sign will be appended to the result if it is needed. private Strin( de(reeToStrin(236 creates a ,tring which represents the current Term"s degree. pu%lic void mer(e2Term %36 merges this term with a given term !degrees
-@/12-

must be e-ual, coefficients are added%. public int compareTo!Term b%: compares this Term to another one. 0nly degrees are ta en into consideration. This method is needed in order to implement the interface #omparable.public double evaluate!double val%: replaces the / variable with a given value. pu%lic Term clone23: clones the current Term with no further modifications. pu%lic Term clone2int scalar36 clones the current Term and multiplies it with a scalar !only modifies the coefficient% public Term clone!int scalar, int power%: clones the current Term and simultaneously multiplies the coefficient with a given scalar and adds a given power to the degree. pu%lic Strin( toStrin(2%oolean include'lus3: converts the Term to a ,tring. The class also provides getter and setter methods for both fields.

2. 5olynomial pu%lic 'olynomial236 constructor2 creates an empty polynomial !has no terms%. pu%lic 'olynomial2'olynomial p36 constructor2 creates a clone of a given polynomial. pu%lic 'olynomial2Strin( line36 parses a given ,tring, creating a polynomial from its mathematical, te$tual representation. private void addTerm2Term currentTerm36 adds a Term to the collection. 'f the Term is already present, it is merged with the colliding Term. private void chec9:eros236 a method which eliminates any null Terms from the collection. pu%lic int compareTo2'olynomial a36 compares this 5olynomial to another one. This method is part of the #omparable interface. pu%lic int (etDe(ree236 returns the degree of the 5olynomial. public double evaluate!double val%: evaluates the 5olynomial"s value for a given /. This is done by summing up all the values produced by its Terms. pu%lic Strin( toStrin(236 converts the 5olynomial"s value to a ,tring. This class also provides static and non-static methods for polynomial operations !addition, subtraction, multiplication, derivation%.

-A/12-

*. <valuator pu%lic 8valuator236 constructor2 creates an empty collection and adds the result polynomial !empty as well% to this set. pu%lic void evaluate0nput2Strin( in36 interprets the command given in the ,tring parameter. pu%lic Strin( (et+ast.esult236 returns a string depicting the last result obtained from a command. pu%lic Strin(;< (et=aria%les236 returns an array of strings containing a description of each polynomial-name pair in the values )ap. pu%lic Strin( (et*essa(e236 gets the last message produced by the evaluator. The class also has a set of private methods, one for each command supported. These methods try to e$ecute their corresponding command, and, on failure, return an appropriate value such that the evaluator passes the control to the ne$t such method. 'f no operation method is able to e$ecute a command based on the input string, an error message is produced. !#"# User 0nterface The user interface is e$clusively implemented in the =raphical'nterface class. 't consists of the following elements: 1. ( multi-line, read only te$t control in which a basic application description is written. 2. ( multi-line, read only te$t control which holds information about the curently stored 2 1 polynomials. The last result will be held here as well, being stored with a special simbol name. 5 *. ( single line te$t control in which the user can type and submit !via the <nter ey% te$t commands for the <valuator to process. 3. ( single line, read only te$t 3 4 control where the last result or error message is printed. 6. (n e$it button.
-1?/12-

(ll relationships modeled within the design phase were of !wea and strong% aggregation. :o inheritance !apart from the =raphical'nterfac which e$tends the >.rame class% was needed in order to solve this problem. Terms are part of a 5olynomial !strong dependency, a Term has no logic of e$isting without a parent 5olynomial% and 5olynomials are part of the <valuator !wea dependency, a 5olynomial may e$ist logically without a parent <valuator%.

. (mp%ementation and Testing


The application code was implemented respecting the module presented so far. The approach was a through a bottom-up techni-ue, so the first class to be implemented was the Term class. <ach module was tested using a test harness !the TestBarness class is still present in the pro+ect%. &ugs were found this was and fi$ed. &ecause of the hierarchy of the design, most bugs could have been propagated upwards to higher levels. Baving this in mind, unit testing was thoroughly used through the implementation phase such that no !or at little as possible% bugs will get propagated this way. (lso, regression testing was an important tool, as some bugs re-emerged in the latter phases of implementation. &ecause of the fact that the evaluator must directly interpret te$t commands issued by the user, e$tra testing was done to assure that no input may trigger an incorrect behavior of the application. 7uring implementation, the command synta$ was also selected. Two types of commands !operations% were developed: binary: addition: C:ameD E C:ameD subtraction: C:ameD - C:ameD multiplication: C:ameD F C:ameD assignment: C:ameD G C:ameD or C:ameD G !C5olynomialD% evaluation: C:ameD H CIalueD unary: derivation: C:ameD" display: C:ameDJ delete: C:ameDK The last result will be stored under the variable name: " ".

). *esu%ts
The final version of the program supports addition, subtraction, multiplication, derivation, evaluation, assignment, disposal and string output of polynomials. 't can perform one operation at a time. ( polynomial can have an indefinite number of terms !only depends on the
-11/12-

memory space that the Tree,et collection can occupy%, with degrees and coefficients values bounded only by the ma$imum and minimum values representable on integertyped variables. The model behind the implementation is well encapsulated, such that further enhancements and e$tensions of the capabilities of the system can be easily added.

+. ,onc%usions
.urther developments: The application can be enhanced by adding new polynomial operations !li e integration, division, etc%. ( template !generic type% may also be created in order to be able to change the type of the term coefficients !e.g. to float instead of integer%. ( command may be added such that the command interpreter reads a command file and e$ecutes in line by line. Logical and comparison operations may be added to the evaluator. .low control operations may also be added if logical operations are supported. 'f the previous three points are implemented, we can already spea of having a sort of programming language created. <nable multi-operation commands, i.e. the ability to group operations such that the evaluator e$ecutes them in the standard, arithmetic order. #reating multi-variable polynomials as an e$tension to single-variable ones, in this case, the evaluate operation should either specify an array of values !one for each variable% or a variable-values pair. 'mplementing other procedures that involve polynomials !for e$ample interpolation%. 7esigning an algorithm that numerically calculates the roots of a given polynomial. <$panding the user interface such that there will be a graphical support for command creation. What have ' learned during the development of this applicationJ The only new elements ' have encountered were the construction of the graphical interface using the Window&uilder plug-in.

-. .ib%iograph&
M1N http://docs.oracle.com M2N http://www.stac overflow.com/ M*N https://www.eclipse.org/windowbuilder/
-12/12-

Das könnte Ihnen auch gefallen