Question:
Help in Executing EVALUATE POSTFIX PROGRAM..(program getting compiled)?
red007
2011-11-06 09:23:49 UTC
Program is getting compiled but is giving ARRAY OUT OF BOUNDS error.
PLEASE HELP FAST !!! HAVE TEST IN 12 Hours..FULL PROGRAM IS GIVEN BELOW

import java.io.*;
class Evaluate
{
char postfix[];
int stack[];
int i,a,b,c,top,n;
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
Evaluate() throws IOException
{
System.out.println("ENTER ARRAY SIZE");
n=Integer.parseInt(input.readLine());
postfix=new char[n];
stack=new int[n];
top=-1;
i=-1;
}

void readpostfix() throws IOException
{
char p;
System.out.println("ENTER STRING");
do
{
p=(char)input.read();
i++;
postfix[i]=p;
}
while(p!='\n');
postfix[i]='\0';
}


boolean isoperand(char c)
{
if(c>='0'&&(c<='9'))

return true;
else
return false;
}

void compute()
{
for(i=0;postfix[i]!='\0';i++)
if(isoperand(postfix[i]))
{
top++;
stack [top]= (int) (postfix[i]-'0');
}
else
{
a=stack[top];
top--;
b=stack[top];

switch(postfix[i])
{
case'+':c=b+a;
stack[top]=c;
break;
case'-':c=b-a;
stack[top]=c;
break;

case'*':c=b*a;
stack[top]=c;
break;
case'/':c=b/a;
stack[top]=c;
break;

default:System.out.println("INVALID OPERATOR");
}
}

System.out.println("THE VALUE OF POSTFIX EXPRESSION IS "+stack[top]);
}

public static void main(String args[])throws IOException
{
Evaluate e=new Evaluate();
e.readpostfix();
e.compute();
}
}
Three answers:
?
2011-11-07 04:12:54 UTC
do

do

{

p=(char)input.read();

i++;

postfix[i]=p; ///when terminated by \n it is reading this char into array and then checking the condition for do-while loop and then terminating from the loop

}

while(p!='\n');

postfix[i]='\0';



Assume your string to be 234+* resulting (2+(3*4)) =14



String here is 234+* and then u hit enter ri8..!!



so the length of the array should be 6 instead of 5(1 more than the string size visble to accomodate \n or later \0 in ur code)



OR ELSE THE REST OF CODE IS PROPER OTHER THAN VALIDATION OF INPUT
rashmi.srin
2011-11-06 10:39:16 UTC
the prob is in the readpostfix function itself... the postfix array is somehow not accepting p

try removing the null character for postfix..

the prog is working if ur dont enter a +-* or /..meaning the parsing pointer is not reading the arithmatic char...

its throwing exception once it reaches + or anything else...



all the best
2016-05-16 14:30:05 UTC
Fail


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...