
Java code
By: a guest on
Dec 13th, 2011 | syntax:
Java | size: 2.56 KB | hits: 72 | expires: Never
import java.util.*;
public class Calculator {
int rc;
static int src;
double result;
String s;
String token;
String operator;
String expr;
String peektoken;
int cursor = 0;
public static void main(String[] args)
{
Calculator x = new Calculator();
src = x.process();
return;
}
int process()
{
Scanner sc = new Scanner(System.in);
boolean keepgoing = true;
while(keepgoing == true)
{
String s = sc.nextLine();
s = s.trim();
if (s== null)
{
keepgoing = false;
continue;
System.out.println("The input is" + s);
result = evalexpr(s);
}
}
return 0;
}
double evalterm()
{
double a = evalfactor();
token = peektoken();
if((token.equals("*")) || (token.equals("/")))
{
operator = token;
cursor++;
double b = evalfactor();
if (operator == "*")
{
a=a*b;
}else{
a=a/b;
}
}
return a;
}
double evalexpr()
{
double x = evalterm();
token = peektoken();
if((token.equals("+")) || (token.equals("-")))
{
operator = token;
cursor++;
double y = evalterm();
if (operator == "+")
z = x + y;
else
z = x - y;
}
return x;
}
double evalfactor()
{
token = peektoken();
if(token.equals("("));
{
cursor++;
double K = evalexpr();
return K;
}
else
{
cursor++;
double m = Double.parseDouble(token);
}
return m;
}
String peektoken()
{
String s = "";
while(cursor<expr.length())
{
s = expr.substring(cursor,cursor+1);
if(s.matches("[0-9]"))
{
return s;
}
if(s.equals(" "))
{
cursor++;
continue;
}
if(s.matches("[+-*/]"))
{
return s;
}
System.out.println("Error");
return s;
}
}
}