Runtime error with Java solution, yet ok in IDE


  • 0
    Y

    Error message:

    Runtime Error Message:
    Line 13: java.lang.NullPointerException
    Last executed input:
    "0"

    Code

    public List<Integer> diffWaysToCompute(String input) {
        if (input == null) {
            return new ArrayList<Integer>();
        }
        List<String> parsedInput = parseInput(input);
    	List<Integer>[][] result = (ArrayList<Integer>[][]) new ArrayList[parsedInput.size()][parsedInput.size()];
        // collect results at each operator dividing point
    	for (int step = 0; step < parsedInput.size(); step += 2) {
    		for (int i = 0; i < parsedInput.size() - step; i++) {
    			int j = i + step;
    			if (step == 0) {
    				result[i][j].add( Integer.parseInt(parsedInput.get(i)) );
    				continue;
    			}
    			for (int k = i + 1; k < j; k++) {
    				for (Integer num1 : result[i][k-1]) {
    					for (Integer num2 : result[k+1][j]) {
    						if ( parsedInput.get(k).equals("+") ) {
    							result[i][j].add(num1 + num2);
    						}
    						if ( parsedInput.get(k).equals("-") ) {
    							result[i][j].add(num1 - num2);
    						}
    						if ( parsedInput.get(k).equals("*") ) {
    							result[i][j].add(num1 * num2);
    						}
    					}
    				}
    			}
    		}
    	}
    	return result[0][parsedInput.size()-1];
    }
    
    private List<String> parseInput(String input) {
    	List<String> result = new ArrayList<String>();
    	for (int i=0; i<input.length(); i++) {
    		if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*') {
    			result.add("" + input.charAt(i));
    			continue;
    		}
    		String one = "";
    		while (i < input.length() && !(input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*')) {
    			one += input.charAt(i++);
    		}
    		i--;
    		result.add(one);
    	}
    	return result;
    }

  • 0
    T

    result[i][j] is never intialized, if you create new ArrayList[3] it will create { null, null, null }.
    Replace all result[i][j].add(num) with add(result, i, j, num) and lazily initialize the lists:

    void add(List<Integer>[][] result, int i, int j, int num) {
        List<Integer> list = result[i][j];
        if (list == null) {
            result[i][j] = list = new ArrayList<>();
        }
        list.add(num);
    }
    

    or add result[j][j] = new ArrayList<>(); in if (step == 0).

    Either way you'll face more problems, like for input 2*3-4*5:

    Line (Integer.parseInt): java.lang.NumberFormatException: For input string: "*"


Log in to reply
 

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