Answer to Question #28403 in Java | JSP | JSF for phanisri

Question #28403
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);
}
}
0
Expert's answer

Answer in progress...

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS