当前位置: 技术问答>java相关
Java中如何计算表达式
来源: 互联网 发布时间:2015-03-26
本文导语: 例如:用户在一个文本框中输入了一个公式:100+2*3 如何计算出结果? | /* * Module : Parser.java * Scope : Logical/Mathematical Parser * Author : A.Conte * Version : 1.0.0 * Revision: 17/09/01 ...
例如:用户在一个文本框中输入了一个公式:100+2*3
如何计算出结果?
如何计算出结果?
|
/*
* Module : Parser.java
* Scope : Logical/Mathematical Parser
* Author : A.Conte
* Version : 1.0.0
* Revision: 17/09/01
* NOTE : this class is a simply expandable Parser that
* now implements only The base math functions (+,-,*,/)
* and the 'log' function and an a ' bool = find(string, subString)'
* function with their priority and is able to recognize
* multiple parenthesis with their precedence.
* Example :
* Expression: (A+B)*log(C*D+E)-F*(G+H*(I*3))
*
* It's the Btree representation of the Expression above:
*
* [-]
* / * [*] [*]
* /| | * [+] [log][F] [+]
* /| | / * [A] [B] [+] [G] [*]
* /| / * [*][E] [H] [*]
* /| / * [C][D] [I] [3]
*
* the Class provide itself to produce the structure represented
* and is possible it's representation in prefix, infix and
* postfix (Hungarian) mode.
*
**** DISCLAIMER:
* This part of software is intented for NO PROFIT and studies only.
* For the use of this source please contact the Author (impeto@libero.it) and
* report his name on about message of your production.
*
* The 'author' makes no representations or warranties about the suitability
* of the software, either expressed or implied, including but not limited to the
* implied warranties of merchantability, fitness for a particular purpose, or
* non-infringement. The 'author' shall not be liable for any damages suffered
* by licensee as a result of using, modifying or distributing this
* software or its derivatives.
****
* @author Antonio Conte (impeto@libero.it)
* Copyright (c) 2001 Antonio Conte. All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* Parsing Class
*/
public class Parser
{
// Definition of walk Modes for Tree
public static String PREFIX_MODE = "PREFIX_MODE";
public static String INFIX_MODE = "INFIX_MODE";
public static String POSTFIX_MODE = "POSTFIX_MODE";
// BTree Struct References
private String data = null;
private Parser left = null;
private Parser right = null;
// Static definitions of separators for Parsing
private static String separators = "+-/*(),";
// Parsing valid operators (the priority is from left to right)
private static String operators[] =
{ ",",
"+", // Math Addition
"-", // Math Substraction
"*", // Math Multiplication
"/", // Math Division
"%", // Math Modulus
"log", // Math n-logarithm
"find" // boolean find( string, subString )
};
// Vector that contains the Expression tokens
private String completeStatement = "";
private ArrayList parts = new ArrayList();
private int numOperators = 0;
/**
* Unique Default Constuctor
*/ public Parser( String Expression ) throws RuntimeException
{
completeStatement = Expression; // Store the complete Expression
splitExpression( Expression ); // Splits Tokens in Expression
parseSyntax(); // Init Parsing...
}
// --- Functions to manipulate BTree -----------------
public void setLeft (Parser l) { left = l; }
public void setRight (Parser r) { right = r; }
public void setData (String d) { data = d; }
public Parser getLeft () { return(left); }
public Parser getRight () { return(right); }
public String getData () { return(data); }
public String toString () { return(""+data); }
// ---------------------------------------------------
/**
* Recursive walk & print Function
*/ public void printWalking( String Mode )
{
if ( Mode.equals(PREFIX_MODE) ) System.out.print( "["+getData()+"]" );
if ( left != null ) left.printWalking(Mode);
if ( Mode.equals(INFIX_MODE) ) System.out.print( "["+getData()+"]" );
if ( right != null ) right.printWalking(Mode);
if ( Mode.equals(POSTFIX_MODE) ) System.out.print( "["+getData()+"]" );
}
/*
* Expression Tokenizator and Store in Parts
*/ private void splitExpression( String Expression )
{
// Temp Classes for conversion
StringTokenizer statements = new StringTokenizer( Expression, separators, true );
String tempToken;
// Renew Parts container
parts.clear();
numOperators = 0;
// Copy Tokens in Vector
while ( statements.hasMoreElements() )
{
// Recognized token
tempToken = (String)statements.nextElement();
// Count operators
for (int i=0; i
* Module : Parser.java
* Scope : Logical/Mathematical Parser
* Author : A.Conte
* Version : 1.0.0
* Revision: 17/09/01
* NOTE : this class is a simply expandable Parser that
* now implements only The base math functions (+,-,*,/)
* and the 'log' function and an a ' bool = find(string, subString)'
* function with their priority and is able to recognize
* multiple parenthesis with their precedence.
* Example :
* Expression: (A+B)*log(C*D+E)-F*(G+H*(I*3))
*
* It's the Btree representation of the Expression above:
*
* [-]
* / * [*] [*]
* /| | * [+] [log][F] [+]
* /| | / * [A] [B] [+] [G] [*]
* /| / * [*][E] [H] [*]
* /| / * [C][D] [I] [3]
*
* the Class provide itself to produce the structure represented
* and is possible it's representation in prefix, infix and
* postfix (Hungarian) mode.
*
**** DISCLAIMER:
* This part of software is intented for NO PROFIT and studies only.
* For the use of this source please contact the Author (impeto@libero.it) and
* report his name on about message of your production.
*
* The 'author' makes no representations or warranties about the suitability
* of the software, either expressed or implied, including but not limited to the
* implied warranties of merchantability, fitness for a particular purpose, or
* non-infringement. The 'author' shall not be liable for any damages suffered
* by licensee as a result of using, modifying or distributing this
* software or its derivatives.
****
* @author Antonio Conte (impeto@libero.it)
* Copyright (c) 2001 Antonio Conte. All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* Parsing Class
*/
public class Parser
{
// Definition of walk Modes for Tree
public static String PREFIX_MODE = "PREFIX_MODE";
public static String INFIX_MODE = "INFIX_MODE";
public static String POSTFIX_MODE = "POSTFIX_MODE";
// BTree Struct References
private String data = null;
private Parser left = null;
private Parser right = null;
// Static definitions of separators for Parsing
private static String separators = "+-/*(),";
// Parsing valid operators (the priority is from left to right)
private static String operators[] =
{ ",",
"+", // Math Addition
"-", // Math Substraction
"*", // Math Multiplication
"/", // Math Division
"%", // Math Modulus
"log", // Math n-logarithm
"find" // boolean find( string, subString )
};
// Vector that contains the Expression tokens
private String completeStatement = "";
private ArrayList parts = new ArrayList();
private int numOperators = 0;
/**
* Unique Default Constuctor
*/ public Parser( String Expression ) throws RuntimeException
{
completeStatement = Expression; // Store the complete Expression
splitExpression( Expression ); // Splits Tokens in Expression
parseSyntax(); // Init Parsing...
}
// --- Functions to manipulate BTree -----------------
public void setLeft (Parser l) { left = l; }
public void setRight (Parser r) { right = r; }
public void setData (String d) { data = d; }
public Parser getLeft () { return(left); }
public Parser getRight () { return(right); }
public String getData () { return(data); }
public String toString () { return(""+data); }
// ---------------------------------------------------
/**
* Recursive walk & print Function
*/ public void printWalking( String Mode )
{
if ( Mode.equals(PREFIX_MODE) ) System.out.print( "["+getData()+"]" );
if ( left != null ) left.printWalking(Mode);
if ( Mode.equals(INFIX_MODE) ) System.out.print( "["+getData()+"]" );
if ( right != null ) right.printWalking(Mode);
if ( Mode.equals(POSTFIX_MODE) ) System.out.print( "["+getData()+"]" );
}
/*
* Expression Tokenizator and Store in Parts
*/ private void splitExpression( String Expression )
{
// Temp Classes for conversion
StringTokenizer statements = new StringTokenizer( Expression, separators, true );
String tempToken;
// Renew Parts container
parts.clear();
numOperators = 0;
// Copy Tokens in Vector
while ( statements.hasMoreElements() )
{
// Recognized token
tempToken = (String)statements.nextElement();
// Count operators
for (int i=0; i