0

When my piece of code below runs on Eclipse on both on Mac and Win8 (both are with Open JDK-17.0.2) below I get the java.lang.NullPointerException: Cannot invoke "javax.script.ScriptEngine.eval(String)" because "engine" is null, while on Visual Studio Code it runs ok.

What is the problem and what should be done to fix the issue ? Your piece of advice would be appreciated. Looking forward to hearing from the community.

import java.util.*;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class uselessSequenceGenerator { 
    public static void main(String[] args) throws Exception {
  
        ArrayList<Character> operators = new ArrayList<Character>(Arrays.asList('*', '/', '+', '-'));
        double number = secretNumGenerator(5, operators);
        //double number = secretNumGenerator(3, operators);
        //double number = secretNumGenerator(8, operators);
        //double number = secretNumGenerator(1, operators);
        //double number = secretNumGenerator(0, operators);
        System.out.println(number);
    }


    public static double secretNumGenerator(int n, ArrayList<Character> operators)
    {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        String ret = "";
        ret += gen(n, operators, ret, 0);
        double result = 0;
        try {
            result = (double)engine.eval(ret);

        } catch (Exception e) {             
            System.out.println(e);

        }
        return result;

    }

    private static String gen(int n, ArrayList<Character> operators, String ret, int i)
    {
        ret += n ;
        if(n > 1)
        {
            ret += operators.get(i);
            ret = gen(n - 1, operators, ret, i + 1) ;
        }
        return ret;
    }
}
Alex
  • 1
  • Here you will find the answer. Visit https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – Konrad Niedźwiedzki Oct 23 '22 at 18:45
  • 1
    Is Visual Studio Code also using JDK 17 to run your code? JavaScript was removed in Java 15. https://www.oracle.com/java/technologies/javase/15-relnote-issues.html#JDK-8236933 – nitind Oct 23 '22 at 19:06

0 Answers0