Anda di halaman 1dari 20

ECSE501 OBJECT ORIENTED DEVELOPMENT

Coursework 1

Module Leader: Mrs. Sriyal Jayasingha


By: R.A.Thushara Kasun Ranawaka
Student ID: 2010066
Group B

Coursework 1
Contents
Acknowledgment ................................................................................................................................................................. 1
Introduction ......................................................................................................................................................................... 1
Overview .......................................................................................................................................................................... 1
Assumptions & Constrains ............................................................................................................................................... 1
Design .................................................................................................................................................................................. 2
Use case diagram ............................................................................................................................................................. 2
Class diagram ................................................................................................................................................................... 2
Code ..................................................................................................................................................................................... 3
class CalculatorTest ......................................................................................................................................................... 3
class Calculator ................................................................................................................................................................ 5
class ArithmeticExpression ............................................................................................................................................ 10
class Addition ................................................................................................................................................................. 10
class Subtraction ............................................................................................................................................................ 10
class Multiplication ........................................................................................................................................................ 11
class Divide .................................................................................................................................................................... 11
class Power .................................................................................................................................................................... 11
class RandomCalculation ............................................................................................................................................... 11
Test Plan ............................................................................................................................................................................ 12
Screen shots................................................................................................................................................................... 13
Conclusion ......................................................................................................................................................................... 17
Attachments ...................................................................................................................................................................... 18
References ......................................................................................................................................................................... 18

0|Page

Coursework 1
Acknowledgment.
Thank you very much everyone who help me to deliver this program

Introduction
Overview
Design and implement an abstract base class ArithmeticExpression that represent any binary (having two
arguments) arithmetic expression. In this coursework you will be implementing various subclasses of this class. The
abstract class should include at least two methods called evaluate and display which are described below.
Design and implement concrete (non-abstract) classes which are subclasses of the class ArithmeticExpression and each
one represent some simple arithmetic expression. The operations that you should implement for each subclass should
include the binary (i.e. accepting exactly two arguments) operations of addition, subtraction, multiplication and
division (all of them accepting double type arguments). Using the classes you should be able to represent an arbitrary
expression (i.e. an expression with an arbitrary number of terms), for example an expression like (5.0+8.1)*(2.0) or
((5.0+8.1)*(2.0))/12.5 (not specically in this format but represent the overall expression in an equivalent way). To
design your classes you should think what common functionality and dierences (elds and methods) these classes
share and place such functionality at the appropriate place of the class hierarchy.
Implement methods evaluate and display. Method evaluate evaluates the arithmetic expression that the object
represents and returns the result as a double. For example, calling it in an object representing expression
(5.0+8.1)*(2.0) should return 26.2. Method display prints the raw (unevaluated) expression on the screen. For
example, calling it in an object representing expression (5.0+8.1)*(2.0) should display the string
(5.0+8.1)*(2.0) (without the quotes). You should NOT use static methods!
Implement a test class CalculatorTest which tests the functionality of your classes (the methods of your classes should
be called and make sure that they do what they are supposed to do). Implement a class RandomCalculations which
automatically creates a random number of random expressions and uses your classes above to evaluate and display
them. Every time that this class is run, a dierent number of dierent random expressions is evaluated and displayed.
Test its functionality by calling its methods in the CalculatorTest class above.

Assumptions & Constrains


This program works like a manual calculator like we use in our day to day works. It calculates the equation left side to
right side. If youre entering a equation with brackets you should close the bracket in order to get an answer. I use
eclipse indigo for the development of this calculator program.

1|Page

Coursework 1
Design
Use case diagram
System
EnterEquation
ErrorInput
<<include>>

DisplayEquation

User

<<extend>>

DisplayAnswer

CalculateEquation
DisplayResult

RandomGenarateEquation

Class diagram
Calculator
+bodmas: boolean
+brOpCount: int
+brClCount: int
+opCount: int
+token: String
+delims: String
+temp: String
+opArr: String
+count: int

CalculatorTest
+userInput: String
+userInput2: String
+equation: String
+calculateMain(): void

+toStrings(double: in): String


+toDouble(String: in): double
+calculate(String: equation): void
+expression(String: equ): void
+extractValue(String: s, int: start): String
+checkOperator(char: ch, double: x, double: y): boolean
+getOperator(char: ch): String

RandomCalculation
+randomDouble1: double
+randomDouble2: double
+randomOperator:int
+theString: String
+passString(): String

ArithmeticExpression
+evaluate(double: x, double: y): double
+display(String: eqation, String: answer): void

Addition

Multiplication

+evaluate(double: x, double: y): double


+display(String: eqation, String: answer): void

Subtraction

+evaluate(double: x, double: y): double


+display(String: eqation, String: answer): void

+evaluate(double: x, double: y): double


+display(String: eqation, String: answer): void
Divide
+evaluate(double: x, double: y): double
+display(String: eqation, String: answer): void

Power
+evaluate(double: x, double: y): double
+display(String: eqation, String: answer): void

2|Page

Coursework 1
Code
class CalculatorTest
package Calaculator;
import java.util.Scanner;
public class CalculatorTest {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String usrInput=" ",usrInput2=" ",equation=" ";

System.out.println("__________________________________________________________________________");
System.out.println("_____________________________CALCULATOR v0.1______________________________");
System.out.println("_____________________________---------------______________________________");
System.out.println("__________________________THUSHARA KASUN RANAWAKA_________________________");
System.out.println("___________________________---------------------__________________________");
System.out.println("__________________________________________________________________________");
int j=0;
while(j<1){
j++;
System.out.println();
System.out.println(" MAIN MENU");
System.out.println("-------------");
System.out.println();
System.out.println("1. User inputs");
System.out.println("2. Manul inputs");
System.out.println("3. Exit");
System.out.println();
System.out.print("Enter a number to continue: ");
int i=0;
while(i<1){
i++;
usrInput = scan.nextLine();
if (usrInput.trim().equals(""))
{
System.out.println("No input detacted!");
System.out.println("Re-enter number: ");
i=0;
}
else if(usrInput.equals("1")){
System.out.println("Enter your equation: ");
equation=scan.nextLine();
Calculator c= new Calculator();
c.calculate(equation);
System.out.print("To go back to main menu press 1 [press any key to exit!]: ");

3|Page

Coursework 1
int k=0;
while(k<1){
k++;
usrInput2 = scan.nextLine();
if (usrInput.trim().equals(""))
{
System.out.println("No input detacted!");
System.out.println("Re-enter number: ");
k=0;
}
else if(usrInput2.equals("1")){
j=0;
}
else{
System.out.println(" Exit...");
System.exit(3);
}
}
}
else if(usrInput.equals("2")){
System.out.println("Manul inputs: ");
System.out.println();
ArithmeticExpression ad = new Addition();
ad.evaluate(2.3, 5.3);

ArithmeticExpression ad2 = new Subtraction();


ad2.evaluate( 5.3,2.3);

ArithmeticExpression ad3 = new Multiplication();


ad3.evaluate(2.5, 4);

ArithmeticExpression ad4 = new Divide();


ad4.evaluate(25,0.5);

ArithmeticExpression ad5 = new Power();


ad5.evaluate(2,3);

System.out.println();
Calculator c= new Calculator();
c.calculate("20+30");//50
c.calculate("20-30");//
c.calculate("20*30");//
c.calculate("20/30");//
c.calculate("2^3");//
System.out.println();
c.calculate("2+30+2");//25
c.calculate("20-30-5");//-15
c.calculate("20*30/2");//300
c.calculate("20/30*2");//1.33333333333

4|Page

Coursework 1
c.calculate("2^4/2");//4
System.out.println();
System.out.println("Automatic inputs(random inputs): ");
System.out.println();
RandomCalculation r =new RandomCalculation();
c.calculate(r.passString());
c.calculate(r.passString());
c.calculate(r.passString());
c.calculate(r.passString());
c.calculate(r.passString());
j=0;
}
else if(usrInput.equals("3")){
System.out.println(" Exit...");
System.exit(3);
}
else{
System.out.println("Invalid input!");
System.out.println("Re-enter number: ");
i=0;
}
}
}
}
}

class Calculator
package Calaculator;
import java.util.Stack;

public class Calculator {


private
with brackets.
private
brackets.
private
private
private

Stack<Character> operatorSt = new Stack<Character>();//i use this only for solving equations
Stack<Double> operandSt = new Stack<Double>();//i use this only for solving equations with
String temp;
String opArr = "*/+-^";
int count = 0;

public double toDouble(String in) {


double aDo = Double.parseDouble(in);
return aDo;
}
public String toStrings(double in) {
String aSt = Double.toString(in);

5|Page

Coursework 1
return aSt;
}

public void calculate(String equation){


boolean bodmas=false;
int brOpCount=0,brClCount=0;

for(int i=0;i<equation.length();i++){
if(equation.charAt(i)=='('){
brOpCount++;
continue;
}
if(equation.charAt(i)==')'){
brClCount++;
continue;
}
}
if(brOpCount!=brClCount)
{
System.out.println("ERROR:Incorrect equation!");
System.out.println(" Exit...");
System.exit(3);
}
else if(brOpCount==0 && brClCount==0){
bodmas=false;
}
else{
bodmas=true;
}

if(bodmas==false){
expression(equation);
}
else
{
temp = equation;
char tmpCh = ' ',lastOpCh= ' ';
double tmpNum1=0, tmpNum2 = 0;
double ans = 0.0;
int brOCount=0,brCCount=0;

while (count < temp.length()) {


if (temp.length() > 1 && temp.charAt(count) == '(') {
brOCount++;
operatorSt.push(temp.charAt(count));
if(brOCount>brCCount && brCCount!=0){
lastOpCh=tmpCh;
}
}

6|Page

Coursework 1
else if (temp.charAt(count) == ')') {
brCCount++;
tmpCh = operatorSt.pop();
tmpNum1 = operandSt.pop();
if(!operandSt.isEmpty()){
tmpNum2 = operandSt.pop();
}
else{
tmpNum2 = 0;
}
if(tmpCh=='+'||tmpCh=='*')
ans +=toDouble(getOperator(tmpCh, tmpNum1, tmpNum2));
else if(tmpCh=='-'||tmpCh=='/'||tmpCh=='^')
ans +=toDouble(getOperator(tmpCh, tmpNum2, tmpNum1));
else{
System.out.println("Error.,.,.");
}
}
else if (Character.isDigit(temp.charAt(count))) {
String str = extractValue(temp, count);
operandSt.push(Double.parseDouble(str));
}
else if (checkOperator(temp.charAt(count))) {
operatorSt.push(temp.charAt(count));
}
else {
System.out.println("ERROR:Incorrect equation!");
break;
}
count++;
}
System.out.println(equation +" = "+ans);
}
}
public void expression(String equ){
int opCount=0;
String delims = "[+\\-*/\\^() ]+";
String[] token = equ.split(delims);
int size=equ.length();
for(int i=0;i<equ.length();i++){
if(equ.charAt(i)=='/'){
opCount++;
Divide add1 =new Divide();
double x =toDouble(token[opCount-1]);
double y=toDouble(token[opCount]);

7|Page

Coursework 1
String x2=token[opCount];
token[opCount]=toStrings(add1.evaluate(x,y));
if(i+(x2.length())==size-1){
add1.display(equ,token[opCount]);
}
}
if(equ.charAt(i)=='*'){
opCount++;
Multiplication add1 =new Multiplication();
double x =toDouble(token[opCount-1]);
double y=toDouble(token[opCount]);
String x2=token[opCount];
token[opCount]=toStrings(add1.evaluate(x,y));
if(i+(x2.length())==size-1){
add1.display(equ,token[opCount]);
}
}

if(equ.charAt(i)=='+'){
opCount++;
Addition add1 =new Addition();
double x =toDouble(token[opCount-1]);
double y=toDouble(token[opCount]);
String x2=token[opCount];
token[opCount]=toStrings(add1.evaluate(x,y));
if(i+(x2.length())==size-1){
add1.display(equ,token[opCount]);
}
}
if(equ.charAt(i)=='-'){
opCount++;
Subtraction add1 =new Subtraction();
double x =toDouble(token[opCount-1]);
double y=toDouble(token[opCount]);
String x2=token[opCount];
token[opCount]=toStrings(add1.evaluate(x,y));
if(i+(x2.length())==size-1){
add1.display(equ,token[opCount]);
}
}
if(equ.charAt(i)=='^'){
opCount++;
Power add1 =new Power();
double x =toDouble(token[opCount-1]);

8|Page

Coursework 1
double y=toDouble(token[opCount]);
String x2=token[opCount];
token[opCount]=toStrings(add1.evaluate(x,y));
if(i+(x2.length())==size-1){
add1.display(equ,token[opCount]);
}
}
}
}
public String extractValue(String s, int start) {
int end = start;
while (end < s.length()
&& (Character.isDigit(s.charAt(end)) || s.charAt(end) == '.'))
{
end++;
}
count = end - 1;
return s.substring(start, end);
}
public boolean checkOperator(char ch) {
String s = Character.toString(ch);
if (opArr.contains(s)) {
return true;
}
return false;
}
public String getOperator(char ch, double x, double y) {
String temp = null;
if(ch=='+'){
Addition add1 =new Addition();
temp=toStrings(add1.evaluate(x,y));
return temp;
}
if(ch=='-'){
Subtraction add1 =new Subtraction();
temp=toStrings(add1.evaluate(x,y));
return temp;
}
if(ch=='/'){
Divide add1 =new Divide();
temp=toStrings(add1.evaluate(x,y));
return temp;
}
if(ch=='*'){
Multiplication add1 =new Multiplication();
temp=toStrings(add1.evaluate(x,y));
return temp;
}
if(ch=='^'){

9|Page

Coursework 1
Power add1 =new Power();
temp=toStrings(add1.evaluate(x,y));
return temp;
}
return temp;
}
}

class ArithmeticExpression
package Calaculator;
public abstract class ArithmeticExpression {
public abstract double evaluate(double x,double y);
public abstract void display(String equation,String answer);
}

class Addition
class Addition extends ArithmeticExpression {
public double evaluate(double x,double y){
return x+y;
}
public void display(String equation,String answer){
System.out.println(equation+"="+answer);
}
}

class Subtraction
class Subtraction extends ArithmeticExpression {
public double evaluate(double x,double y){
return x-y;
}
public void display(String equation,String answer){
System.out.println(equation+"="+answer);
}
}

10 | P a g e

Coursework 1
class Multiplication
class Multiplication extends ArithmeticExpression {
public double evaluate(double x,double y){
return x*y;
}
public void display(String equation,String answer){
System.out.println(equation+"="+answer);
}
}

class Divide
class Divide extends ArithmeticExpression {
public double evaluate(double x,double y){
return x/y;
}
public void display(String equation,String answer){
System.out.println(equation+"="+answer);
}
}

class Power
class Power extends ArithmeticExpression {
public double evaluate(double x,double y){
return Math.pow(x, y);
}
public void display(String equation,String answer){
System.out.println(equation+"="+answer);
}
}

class RandomCalculation
package Calaculator;
import java.util.Random;
public class RandomCalculation {
public String passString(){
double randomDo=0.0,randomDo2=0.0;
int randomOpe=0,count=0;
String theSt=" ";

11 | P a g e

Coursework 1
Random randomGenerator = new Random();
while( count < 1){
randomDo = randomGenerator.nextInt(999);
randomDo2 = randomGenerator.nextInt(999);
randomOpe = randomGenerator.nextInt(5);
count++;
if(randomDo==randomDo2){
count=0;
}
}
switch (randomOpe)
{
case 0:theSt=randomDo+"+"+randomDo2;
break;
case 1:theSt=randomDo+"-"+randomDo2;
break;
case 2:theSt=randomDo+"*"+randomDo2;
break;
case 3:theSt=randomDo+"/"+randomDo2;
break;
case 4:theSt=randomDo+"^"+randomDo2;
break;
default :
System.out.println("ERROR!");
}
return theSt;
}
}

Test Plan

Test

data

Expcted output

Actual output

ok

1*

20+40

60.0

60

yes

300-0.52

299.48

299.48

yes

60*0.5

30.0

30.0

yes

4*

469/11

42.63

42.63

yes

5*

2^3

8.0

8.0

yes

2.5+45.6+508.3

556.4

556.4

yes

7*

10.33-20.5+45.3-111

-75.87

-75.87

yes

11.5*5/3

19.16

19.16

yes

9*

25/5*4

20.0

20.0

yes

10

4*5*6

120.0

120.0

yes

11*

2/2/2

0.5

0.5

yes

12

8+8-16

0.0

0.0

yes
12 | P a g e

Coursework 1
13

(2+3)+(55+9)

14

(2-3)

15*

(3/2)+(0.5/2)

16

(2+3)-(55+9)

17*

(2-3)/(5.5*2)

18

(3/2)*(0.5/2)

19*

(3.3+2.6)+(2.9+0.1)+(8.8+0.6)

20*

69.0

69.0

yes

-1.0

yes

1.75

yes

69.0

no

10.0

no

1.75

no

18.3

18.3

yes

.1+.6

0.7

0.7

yes

21

(25+2.5

error

error

yes

22

45*8)

error

error

yes

23*

((2*3)+8)+(45.3+0.7)

60.0

60.0

yes

24

((2*3)+8)+(5/2)

16.5

yes

25

(8.2+5.5)/4

13.7

no

26*

(4.4+4.6)*(4*8)

41.0

no

-1.0
1.75
-59.0
-0.09
0.375

16.5
3.425
288

*screen shots shown below

Screen shots

13 | P a g e

Coursework 1

14 | P a g e

Coursework 1

15 | P a g e

Coursework 1

16 | P a g e

Coursework 1

Conclusion
In the implementation time period I had so much trebles building this program such as what is the logic that Im going
to use? Use stack? Linkedlist ? Binary tree? Or something else to build this simple calculator. Then I came up with my
own maths logic to overcome these problems. Its in the program and anyone can understand it. My program read
user entered equation left to right and do the calculation by modifying the equation string itself. It will direct u to 2 if
statements to do the calculations in 2 ways 1 way is equations that have no brackets and equations that have brackets.
Then it will calculate the answer in two different logics. You may feel my code is too long but nothing to do as my logic
I must write so much of code. My program got an issue it is it doesnt calculate equations such as (55+5)-(56/6),(4556)*(8*8) and (45+99)/(5+5). It because lack of time I had to complete this program. But it works well just like a
calculator we use in home.
I know this is not the best way to solve this problem but this is my way of solving it. I made this program in very
limited time period like 4 days so it may have some small mistakes that I didnt have time to correct them.

17 | P a g e

Coursework 1
Attachments

References

. 2011. . [ONLINE] Available at: http://cslibrary.stanford.edu/103/LinkedListBasics.pdf. [Accessed 03 November


2011].

Linked Lists Tutorial, Examples, and Java code. 2011. Linked Lists Tutorial, Examples, and Java code.
[ONLINE] Available at:http://www.mycstutorials.com/articles/data_structures/linkedlists. [Accessed 03 November
2011].

Linked list - Wikipedia, the free encyclopedia. 2011. Linked list - Wikipedia, the free encyclopedia. [ONLINE]
Available at: http://en.wikipedia.org/wiki/Linked_list. [Accessed 03 November 2011].
A Beginners Guide to Big O Notation Rob Bell. 2011. A Beginners Guide to Big O Notation Rob Bell.
[ONLINE] Available at: http://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/. [Accessed 03 November
2011].

Adjacency list - Wikipedia, the free encyclopedia. 2011. Adjacency list - Wikipedia, the free encyclopedia.
[ONLINE] Available at:http://en.wikipedia.org/wiki/Adjacency_list. [Accessed 14 November 2011].

The End
18 | P a g e