中缀式转后缀式工具类实现 (二)

2014-11-24 11:03:48 · 作者: · 浏览: 1
*
*/
public static boolean isLowerOfPriority(char ch1, char ch2)
{
int priority1 = getPriority(ch1);
int priority2 = getPriority(ch2);

return priority1 <= priority2;
}

/**
*
*

* 是否字母
* @param ch
* @return
*/
private static boolean isCharacter(char ch)
{
return (ch >= Operators.LOWER_CASE_A && ch <= Operators.LOWER_CASE_Z)
|| (ch >= Operators.UPPER_CASE_A && ch <= Operators.UPPER_CASE_Z);
}

/**
*
*

* 字符是否数字
*
* @param ch
* @return
*/
private static boolean isNumber(char ch)
{
return ch <= Operators.NINE && ch >= Operators.ZERO;
}

/**
*
*

* 获取操作符的优先级
*
* @param ch
* @return
*/
private static int getPriority(char ch)
{
if (getPriorities().containsKey(ch))
{
return getPriorities().get(ch);
}
return Operators.ERROR_PRIORITY;
}

/**
* 获取 priorities
*
* @return 返回 priorities
*/
private static Map getPriorities()
{
return priorities;
}
}

import java.util.HashMap;
import java.util.Map;

/**
*


* 操作符处理工具类
*
* @author dobuy
* 修改时间: 2013-5-22
*

*/
public final class OperatorUtils
{
/**
* 保存所有操作符(Key)及优先级(Value)
*/
private static final Map priorities;

private OperatorUtils()
{
}

/**
* 类加载时初始化
*/
static
{
priorities = new HashMap();

getPriorities().put(Operators.OPEN_BRACKET, Operators.HIGH_PRIORITY);
getPriorities().put(Operators.MULTIPLITICATION, Operators.MIDIUM_PRIORITY);
getPriorities().put(Operators.DIVISION, Operators.MIDIUM_PRIORITY);
getPriorities().put(Operators.COMPLIMENT, Operators.MIDIUM_PRIORITY);
getPriorities().put(Operators.ADD, Operators.LOW_PRIORITY);
getPriorities().put(Operators.SUBRACTION, Operators.LOW_PRIORITY);
}

/**
*

* 字符是否是操作符(除了字母和数字都是操作符)
*
* @param ch
* @return
* @author dobuy
* 修改时间: 2013-5-22
*/
public static boolean isOperator(char ch)
{
return !isCharacter(ch) && !isNumber(ch);
}

/**
*
*

* ch1的优先级是否不高于ch2
*
* @param ch1
* @param ch2
* @return
*

*/
public static boolean isLowerOfPriority(char ch1, char ch2)
{
int priority1 = getPriority(ch1);
int priority2 = getPriority(ch2);

return priority1 <= priority2;
}

/**
*
*

* 是否字母
* @param ch
* @return
*/
private static boolean isCharacter(char ch)
{
return (ch >= Operators.LOWER_CASE_A && ch <= Operators.LOWER_CASE_Z)
|| (ch >= Operators.UPPER_CASE_A && ch <= Operators.UPPER_CASE_Z);
}

/**
*
*

* 字符是否数字
*
* @param ch
* @return
*/
private static boolean isNumber(char ch)
{
return ch <= Operators.NINE && ch >= Operators.ZERO;
}

/**
*
*

* 获取操作符的优先级
*
* @param ch
* @return
*/
private static int getPriority(char ch)
{
if (getPriorities().containsKey(ch))
{
return getPriorities().get(ch);
}
return Operators.ERROR_PRIORITY;
}

/**
* 获取 priorities
*
* @return 返回 priorities
*/
private static Map getPriorities()
{
return priorities;
}
}

表达式处理工具类:

[java] import java.util.Stack;

/**
*


* 中缀表达式变后缀表达式工具类
*
* @author dobuy
* 修改时间: 2013-5-22