你可以先判断运算符号,然后再做计算.如:
char cflag;
String iText = "100+2*3";
cflag = iText.substring(int,int);
swich (cflag){
case '+'
break;
case '-'
break;
case '*'
break;
case '/'
break;
}
....
不过你还得判断运算符的级别以及有没有扩符,唉,这样是不是太麻烦了?有没有更好的方法?
char cflag;
String iText = "100+2*3";
cflag = iText.substring(int,int);
swich (cflag){
case '+'
break;
case '-'
break;
case '*'
break;
case '/'
break;
}
....
不过你还得判断运算符的级别以及有没有扩符,唉,这样是不是太麻烦了?有没有更好的方法?
* 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 ([email protected]) 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 ([email protected])
* 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 < operators.length; i++ )
if ( tempToken.equals(operators[i]) )
numOperators++; // Copy in Parts Vector
parts.add( tempToken );
}
} /**
* Recursive Syntax Analysys
*/ private void parseSyntax() throws RuntimeException
{
String actToken = ""; // Actual Token for scan process
int level = 0; // Dynamic Parentesis Level
int foundPriority = Integer.MAX_VALUE; // Priority of founded Operator
int foundLevel = Integer.MAX_VALUE; // Parentesis Level of founded Operator
int foundPosition = -1; // founded Operator position
String foundOperator = ""; // founded Operator // If there aren't operators SubExpr is final
if ( numOperators == 0 )
{
setData( (String)parts.get(0) );
return;
} // choose greater priority Token
for ( int position=0; position < parts.size(); position++ )
{
// Token to Analyze
actToken = (String)parts.get(position); // Adjust Parentesis level
if ( actToken.equals("(") ) { level++; continue; }
if ( actToken.equals(")") ) { level--; continue; } // Find best Operator
for (int prior=0; prior < operators.length; prior++) // Scans operators
if ( actToken.equals( operators[prior] ) ) // Compare operators
if ( level < foundLevel ||
( level == foundLevel && prior < foundPriority ) )
{
foundLevel = level;
foundPriority = prior;
foundPosition = position;
foundOperator = actToken;
break;
}
} // check final level: improper parentesys in expression
if ( level !=0 )
throw new RuntimeException("SINTAX ERROR: Check parentesis."); // Check to semplify external parentesis
// CASE: parameters for complex Functions
if ( foundLevel != Integer.MAX_VALUE && foundLevel > 0 )
{
// Check external parentesis
if ( !((String)parts.get( 0 )).equals("(") ||
!((String)parts.get( parts.size()-1 )).equals(")") )
throw new RuntimeException("SYNTAX ERROR: Is not possible to proceed.\n" +
"CASE: Semplifying '()' EXPR:" + completeStatement ); // Remove external parentesis
completeStatement = completeStatement.substring(1, completeStatement.length()-1 ); // Re-submit new simplified expression {Recursion}
splitExpression( completeStatement );
parseSyntax(); // now is possible to quit
return;
} String leftPart = ""; // Left SubPart of Expression
String rightPart = ""; // Right SubPart of Expression // Compose SubStrings Left and Right to analyze
for ( int i=0; i<parts.size(); i++ )
if ( i < foundPosition )
leftPart = leftPart.concat( (String)parts.get(i) );
else
if ( i != foundPosition )
rightPart = rightPart.concat( (String)parts.get(i) ); // ---- Save Founded Operator ----
setData( foundOperator );
// ------------------------------- // Check if is a complex operator
// like log(x), find(Str,substr)
if ( leftPart.equals("") && !foundOperator.equals("") )
{
// TODO: Is possible to count Parameters for specific functions if ( foundOperator.equals("log") )
System.out.println("Founded Function Log..."); //
// HERE: You can insert checks for
// complex operators like log, find, etc.
// /////////////////////////////////////
// Submit Parameters for Analisys
/////////////////////////////////////
setRight( new Parser(rightPart) );
}
else // Case simplex Math Operators
{
// Ricursive Analysys for Left and Right branches
setLeft ( new Parser(leftPart) );
setRight ( new Parser(rightPart) );
}
} // END-PARSER
}---------------------------------------------------------------------------------
FILE: TestParser.java
import Parser;
public class TestParser
{
public static void main( String args[] )
{
// Simply Expression Definition to Parse
String Expression = "find((A+B)*log(C*D+E),F*(G+H*(I*3)))"; Parser ps = null; // Expression Parsing
try
{
ps = new Parser( Expression );
}
catch (Exception e)
{
e.printStackTrace();
} System.out.println("Original Expression: " + Expression ); System.out.print("\nPREFIX: "); ps.printWalking(Parser.PREFIX_MODE);
System.out.print("\nINFIX: "); ps.printWalking(Parser.INFIX_MODE);
System.out.print("\nPOSTFIX: "); ps.printWalking(Parser.POSTFIX_MODE);
System.out.println("");
}
}