i am getng an error that
Exception in thread "main" java.lang.ArrayIndexOutofBoundsException: -1
at pfix.pop(pfix.java:25)
at pfix.evaluate(pfix.java:47)
at pfix.main(pfix.java:88)
my program is to evaluate a postfix expression
import java.io.*;
import java.lang.Math;
class pfix
{
int top,j,i;
String str;
char t,postfix[];
int s[];
DataInputStream in;
public pfix()
{
top=-1;i=0;
postfix=new char[30];
s=new int[30];
in=new DataInputStream(System.in);
}
public void push(int val)
{
top++;
s[top]=val;
}
public int pop()
{
int val;
val=s[top];
top--;
return val;
}
public void evaluate(String str)throws IOException
{
int op1,op2,value=0;
char t;
while(i<str.length())
{
t=str.charAt(i);
if((t>='a' && t<='z')||(t>='A' && t<='Z'))
{
System.out.println("Enter value for "+t+":");
value=Integer.parseInt(in.readLine());
push(value);
}
else
{
switch(t)
{
case '+':
op2=pop();
op1=pop();
value=op1+op2;
push(value);
break;
case '-':
op2=pop();
op1=pop();
value=op1-op2;
push(value);
break;
case '*':
op2=pop();
op1=pop();
value=op1*op2;
push(value);
break;
case '/':
op2=pop();
op1=pop();
value=op1/op2;
push(value);
break;
case '^':
op2=pop();
op1=pop();
value=(int)Math.pow((float)op1,(float)op2);
push(value);
break;
}
}
i++;
}
System.out.println("postfix evaluated val="+value);
}
public static void main(String[] args)throws IOException
{
String str;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter a string:");
str=in.readLine();
(new pfix()).evaluate(str);
}
}
Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…
APPROVED BY CLIENTS
"assignmentexpert.com" is professional group of people in Math subjects! They did assignments in very high level of mathematical modelling in the best quality. Thanks a lot
Comments
Leave a comment