2014-02-16 81 views
1

说一个字符串包含表达式1 < 3 ...如何在if语句中评估该表达式?在if语句中评估字符串中的表达式

import java.io.*; 

public class EvaluateExpression 
{ 
    public static void main(String[]args)throws IOException 
    { 
    InputStreamReader isr = new InputStreamReader(System.in); 
    BufferedReader in = new BufferedReader(isr); 

     String expression; 

     System.out.print("Enter the expression to evaluate: "); 
     expression = in.readLine(); 

     if (expression){ 
     System.out.print("The expression " + expression + " is true."); 
     }else{ 
     System.out.print("The expression " + expression + " is not true."); 
     }   
    } 
} 

需要一个布尔值,但找到一个字符串。有没有一种方法来评估字符串,所以它返回一个布尔值? if (1<3) {...}工作但if (expression) {...}其中字符串变量表达式为1 < 3不起作用。将其转换为布尔值也不起作用。

谢谢!

+3

相似问题:http://stackoverflow.com/questions/2605032/using-eval-in-java – Allan

回答

0

您可以分割使用> <字符串,> =,< =,= =,=为定界符!从分割函数中检查返回数组中的2个字符串,并将它们转换为int。

然后使用类似这样的功能

if (youroperator.equals("<")) 
    return first_number < second_number 
elseif (youroperator.equals(">")) 
    return first_number>second_number 
... 

您的运营商可以从string.contains()函数

+0

管理得到正确的结果使用您的建议......非常感谢! –

+0

很高兴我能帮到队友。 –

0

您可以使用ScriptEngine未来与JDK1.6

例如:

ScriptEngineManager sem = new ScriptEngineManager(); 
ScriptEngine se = sem.getEngineByName("JavaScript"); 

InputStreamReader isr = new InputStreamReader(System.in); 
BufferedReader in = new BufferedReader(isr); 
String expression; 

    System.out.print("Enter the expression to evaluate: "); 
    expression = in.readLine(); 
    String result = se.eval(expression).toString(); 
    if (result.equals("true")) { 
     System.out.print("The expression " + expression + " is true."); 
    } else { 
     System.out.print("The expression " + expression + " is not true."); 
    } 
0

如果你愿意,你可以使用内置的脚本引擎的通用解决方案来获得JVM。

import javax.script.ScriptEngineManager; 
import javax.script.ScriptEngine; 
... 
... 
String expression = "1<3"; 
ScriptEngineManager manager = new ScriptEngineManager(); 
ScriptEngine jsEngine = manager.getEngineByName("JavaScript"); //BE CAREFUL about the engine name. 
Object result = jsEngine.eval(expression); //Returns a java.lang.Boolean for the expression "1<3" 

注:虽然“的JavaScript引擎”的名字在我的环境中工作,在您的环境中可能无法使用,或者可以通过如“JS”或“JavaScript的”其他名字被调用。在某些环境中,其他引擎(如“Groovy”引擎)可能可用。使用您的环境中可用的任何引擎。

0

尝试...

if(expression.equals("1<3")) 
{} 
else 
{} 

“如果”需要布尔作为参数,则不能在it.So有传递一个字符串equals方法java.lang.String中它检查两个字符串是否相等或不是,其返回类型是布尔值(true或false)。