calculateExpression.java

//Calculate the expression like "99+87" or "99-87" or "99*87" or "99/87"
import java.io.*; // for I/O
////////////////////////////////////////////////////////////////
class Design
{
String in;
int maxSize;
public Design(String input)
{
in = input;
maxSize = in.length();
}
public String substr(String input,int pos1,int pos2)
{
String tamp = "";
for(int i = pos1;i<= pos2;i++)
{
tamp = tamp+in.charAt(i);
}
return tamp;
}
public float calculate()
{
int pos = 0;
for(int i = 0;i<maxSize;i++)
{
if((in.charAt(i)=='+')||(in.charAt(i)=='-')||(in.charAt(i)=='*')||(in.charAt(i)=='/'))
{
pos = i;
break;
}
}
String sub1 = substr(in,0,pos-1);
String sub2 = substr(in,pos+1,maxSize-1);
int num1 = Integer.parseInt(sub1);
int num2 = Integer.parseInt(sub2);
switch(in.charAt(pos))
{
case '+':
return (num1+num2);
case '-':
return (num1-num2);
case '*':
return (num1*num2);
case '/':
return (float)(num1/num2);
default:
return -999999;
}
}
}

class calculateExpression
{
public static void main(String[] args)
{
String exam11 = "909+456";
String exam12 = "909-456";
String exam13 = "909*456";
String exam14 = "90/45";
Design exam21 = new Design(exam11);
Design exam22 = new Design(exam12);
Design exam23 = new Design(exam13);
Design exam24 = new Design(exam14);

float result = exam21.calculate();
System.out.println("the result is:"+result);
result = exam22.calculate();
System.out.println("the result is:"+result);
result = exam23.calculate();
System.out.println("the result is:"+result);
result = exam24.calculate();
System.out.println("the result is:"+result);
}
}

calculate

Happy calculating 🙂

Advertisements

2 thoughts on “calculateExpression.java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s