What's wrong with my code(using JAVA)


  • 0
    L

    I get right answer and run without error if I run the code in my computer(jar 1.7),but it always error in OJ.
    there is the code:

    public class Solution {
        public int evalRPN(String[] tokens) {
            int numberOfOperator = 0;
            for(int i = 0; i < tokens.length; i++){
                if(tokens[i].compareTo("0") < 0){
                    tokens[i] = "" + resultForOperate(tokens[i - 2], tokens[i - 1], tokens[i]);
                    numberOfOperator++;
                    for(int j = i - 1; j >= 2 * numberOfOperator; j--){
                        tokens[j] = tokens[j - 2];
                    }
                }
            }
            return Integer.valueOf(tokens[tokens.length - 1]).intValue();
        }
        
        public int resultForOperate(String s1, String s2, String operator){
            int i1 = 0;
            int i2 = 0;
            int result = 0;
            i1 = Integer.valueOf(s1).intValue();
            i2 = Integer.valueOf(s2).intValue();
            switch(operator){
                case "+" :
                    result = i1 + i2;
                    break;
                case "-" :
                    result = i1 - i2;
                    break;
                case "*" :
                    result = i1 * i2;
                    break;
                case "/" :
                    result = i1 / i2;
                    break;
            }
            return result;
        }
    }
    

    Submission Result: Runtime Error

    Runtime Error Message: Line 6: java.lang.ArrayIndexOutOfBoundsException: -1
    Last executed input: ["3","-4","+"]


  • 0
    L

    I've get it, if(tokens[i].compareTo("0") < 0) is the reason, I wrote it to distinguish operator from others, but I forgot there were such tokens like "-4". The result of "-4".compareTo("0") < 0 is true. It cause the ArrayIndexOutOfBoundsException


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.