Thanks , there was some problem at my end. Okay now i am trying to implement an infix calculator . I have written down all the code but i am having problem , if my input is without any parenthesis then i get a nullPointerException in the switch , and when i give an expression with parenthesis it goes in infinite loop .
class d8
{
public static int eVal(String s)
{ int t=0;
char temp;
String tStr="";
for(int i=0;i<s.length();i++)
{
temp=s.charAt(i);
if( Character.isDigit(temp) )
{
tStr +=temp;
intStack.push( Integer.parseInt(tStr) );
}
else
{
switch(temp)
{
case '(':
charStack.push(temp);
break;
case '*':
if( charStack.isEmpty() )
charStack.push(temp);
else if (prec(temp) > prec(charStack.top()) )
charStack.push(temp) ;
else
{
while ( !charStack.isEmpty() && prec(temp) <= prec(charStack.top()) )
{
apply(intStack,charStack);
charStack.push(temp) ;
}
}
break;
case '+':
if( charStack.isEmpty() )
charStack.push(temp);
else if ( prec(temp) > prec(charStack.top()) ) [B]// NULL POINTER EXCEPTION HERE[/B]
charStack.push(temp) ;
else
{
while ( !charStack.isEmpty() && prec(temp) <= prec(charStack.top()) )
{
apply(intStack,charStack);
charStack.push(temp) ;
}
}
break;
case '-':
if( charStack.isEmpty() )
charStack.push(temp);
else if (prec(temp) > prec(charStack.top()) )
charStack.push(temp) ;
else
{
while ( !charStack.isEmpty() && prec(temp) <= prec(charStack.top()) )
{
apply(intStack,charStack);
charStack.push(temp) ;
}
}
break;
case '/':
if( charStack.isEmpty() )
charStack.push(temp);
else if (prec(temp) > prec(charStack.top()) )
charStack.push(temp) ;
else
{
while ( !charStack.isEmpty() && prec(temp) <= prec(charStack.top()) )
{
apply(intStack,charStack);
charStack.push(temp) ;
}
}
break;
case ')':
while (charStack.top() != '(')
{
apply(intStack,charStack);
charStack.pop() ;
break;
}
}
}
}
while(!charStack.isEmpty())
{
apply(intStack,charStack);
result = intStack.top();
}
return 0;
}
public static void apply(GenericStack<Integer> v, GenericStack<Character> o)
{
int rightVal=0,leftVal=0;
rightVal = v.pop();
leftVal = v.pop();
char nextOp = o.pop();
switch (nextOp)
{
case '+':
result =leftVal + rightVal;
intStack.push(result);
break;
case '-':
result =leftVal - rightVal;
intStack.push(result);
break;
case '*':
result =leftVal * rightVal;
intStack.push(result);
break;
case '/':
result =leftVal / rightVal;
intStack.push(result);
break;
}
}
public static int prec(char op)
{
if(op=='+' || op=='-')
return 1;
else if(op=='*'|| op=='/'|| op=='%')
return 2;
else
return 0;
}
public static boolean isOperator(char op)
{
if (op=='+' ||op=='-' ||op=='*' ||op=='/' ||op=='(' ||op==')')
return true;
else
return false;
}
public static void main(String argv[])
{
String s="(((3 + 2)*6) % 4 ) ";
s=s.replaceAll(" ","");
eVal(s);
System.out.println("Result : "+ result);
}
static GenericStack<Integer> intStack = new GenericStack<Integer>();
static GenericStack<Character> charStack = new GenericStack<Character>();
static int result=0;
}
What exactly is the problem?