Search code examples
javaruntime-errorpostfix-notation

NZEC runtime error on SPOJ


My code is running successfully on ideone but is showing NZEC runtime error on SPOJ. Can someone please explain what is wrong with my code?

import java.util.*;
class tuna{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        String[] str = new String[100];
        String pri = "+-*/^";

        Stack<String> stack = new Stack<String>();
        for(int i = 0; i<N; i++){
           str[i]=in.nextLine();
        }

    for(int i = 0; i<N; i++){
        for (int j = 0; j<str[i].length(); j++){
            char ch = str[i].charAt(j);
            if(Character.isLetter(ch))
                System.out.print(ch);
            else if(ch == '('){
                stack.push("(");
            }
            else if(ch == ')' )
            {
                while(!stack.isEmpty() && stack.lastElement()!="("){
                    System.out.print(stack.pop());

                }
                stack.pop();
            }
            else
            {
                while(!stack.empty() && stack.lastElement()!="(" && pri.indexOf(ch)<= pri.indexOf(stack.lastElement()))
                {
                    System.out.print(stack.pop());
                }
                stack.push(Character.toString(ch));
            }
        }
        while(!stack.isEmpty())
        {

            stack.pop();
        }
        System.out.println();
    }
    in.close();

  }
}

would be grateful for some insight on NZEC error. Thank you. test cases(as given on spoj) :

Input:
3
(a+(b*c))
((a+b)*(z+x))
((a+t)*((b+(a+c))^(c+d)))

Output:
abc*+
ab+zx+*
at+bac++cd+^*

Solution

  • Looking from your code. Mistake is using in.nextLine() . Check Using scanner.nextLine() .

    Correction : change to in.next()

     for(int i = 0; i<N; i++) {
         str[i]=in.next();
     }
    

    And I really suggest you to use BufferedReader instead of Scanner for SPOJ questions for better performance