Divide by zero exception but works fine in eclipse


  • 0
    D

    The online judge is hitting a divide by zero exception, yet when I copy/paste my code into eclipse and run it with the exact same test case, it works fine. Here's the code:

    package solutions;
    
    import java.util.Stack;
    
    public class ReversePolishNotation {
        public int evalRPN(String[] tokens) {
            Stack<Integer> numStack = new Stack<Integer>();
            
            for (int i = 0; i < tokens.length; i++)
            {
                if (isInteger(tokens[i]))
                {
                    numStack.push(Integer.parseInt(tokens[i]));
                }
                else
                {
                    int right = numStack.pop();
                    int left = numStack.pop();
                    int result = 0;
                    
                    if (tokens[i] == "+")
                    {
                        result = left + right;
                    }
                    else if (tokens[i] == "-")
                    {
                        result = left - right;
                    }
                    else if (tokens[i] == "*")
                    {
                        result = left * right;
                    }
                    else
                    {
                        result = left / right;
                    }
                    numStack.push(result);
                }
            }
            
            return numStack.pop();
        }
        
        private static boolean isInteger(String s)
        {
            try
            {
                Integer.parseInt(s);
            }
            catch (NumberFormatException nfe)
            {
                return false;
            }
            
            return true;
        }
    }
    

    And here's my unit test for the testcase it's failing.

    public class _ReversePolishNotationTests {
    
    	private ReversePolishNotation rpn = new ReversePolishNotation();
    	
    	@Test
    	public void testCase() {
    		
    		String[] input = {"4","-2","/","2","-3","-","-"};
    		int result = rpn.evalRPN(input);
    		assertEquals(-7, result);
    	}
    }

  • 0
    D

    Nevermind, I figured it out. The bug was using "==" to compare string values as opposed to string.equals(). Strictly speaking, "==" compares references while string.equals() compares values. I guess eclipse and the OJ are running different interpreters.


Log in to reply
 

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