添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

JavaScript eval in JavaApplication: "javax.script.scriptException: Expected operand but found"

Ask Question

In my Java Application, Im relying on JavaScript, implemented via ScriptEngine, to interpret and calculate some basic mathequations I read from a String.

Here is what Ive got:

public void calc(String comp){
try {
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine eng = mgr.getEngineByName("JavaScript");
            res[k] = (Integer) eng.eval(comp);
        } catch (Exception e){
            System.out.println("Error in res: " +e);

No matter which input, excuting will result in:

Error in res: javax.script.ScriptException: :1:5 Expected an operand but found , [3, -, 3] ^ in at line number 1 at column number 5, here with exemplary input comp = "3-3"

Error in public int[] res: javax.script.ScriptException: :1:6 Expected an operand but found * [-12, *, 3] ^ in at line number 1 at column number 6

I dont know JavaScript so I dont know what to do in order to fix this error.

It looks like the string is a stringified array, so you'll either need to join() the array in JavaScript before you pass it to your Java app, or write some Java code to do so. It would help to see the JS code that is using this Java. – Andy Feb 25, 2016 at 15:34

It looks like the string is a stringified array, so you'll either need to join() the array in JavaScript before you pass it to your Java app, or write some Java code to do so.

Here's the JavaScript code:

var str = [3, '-', 3].join(''); // "3-3"
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.