Search code examples
javabeanshell

beanshell newbie- getting error when running simple script


I am trying to run a simple switch-case statement in Beanshell

This is the code I am trying to run--

temp = assignee.toString();
switch( temp.toString() ) 
 {
case 'missing' : check = "missing"; break;
case '404' : check = "404"; break;
default: check = "data"; break;
}

But I am getting the following error--

 ERROR - Error during script execution: Sourced file: inline evaluation of: ``temp = assignee.toString(); switch( temp.toString() ) { case 'missing' : check = . . . '' Token Parsing Error: Lexical error at line 3, column 8.  Encountered: "i" (105), after : "\'m"
 org.webharvest.exception.ScriptException: Error during script execution: Sourced file: inline evaluation of: ``temp = assignee.toString(); switch( temp.toString() ) { case 'missing' : check = . . . '' Token Parsing Error: Lexical error at line 3, column 8.  
Encountered: "i" (105), after : "\'m"
at org.webharvest.runtime.scripting.BeanShellScriptEngine.eval(Unknown Source)

What am I doing wrong here? How do I resolve this error?


Solution

  • String literals in BeanShell, like in Java, must use double-quotes, not single quotes:

    bsh % x = 'missing';
    // Error: Error parsing input: bsh.TokenMgrError: Lexical error at line 1, column 37.  Encountered: "i" (105), after : "\'m"
    bsh % x = "missing";
    bsh % print(x);
    missing
    bsh % 
    

    Single quotes are for character literals. Using single-quotes for a multi-character string gives you an error such as Encountered: "i" (105), after : "\'m", and this is because BeanShell was expecting another ' after the m (to end the character literal), but it got i instead.