|
|||||||||||
| 前のクラス 次のクラス | フレームあり フレームなし | ||||||||||
| 概要: 入れ子 | フィールド | コンストラクタ | メソッド | 詳細: フィールド | コンストラクタ | メソッド | ||||||||||
java.lang.Object | +--jp.ne.ytp.util.ReversePolish
いわゆる逆ポーランド記法(後置記法)を実現します。
渡された計算式を、指定の演算子とその優先順位に従って逆ポーランド記法に変換します。
演算子や優先順位を利用する側で全て決定できるため、
当クラスの利用は四則演算に限定されません。
「カッコ()」の優先順位も外部で指定する必要がありますが、
一般的な利用をする場合、開きカッコは最高位、
閉じカッコは最低位として設定してください。
次のコードは四則演算を実現する簡単な例です。
ArrayList before = new ArrayList();
before.add("1");
before.add("+");
before.add("2");
before.add("*");
before.add("a");
HashMap operators = new HashMap();
operators.put(ReversePolish.OPENPBRACKET, new Integer(50));
operators.put(ReversePolish.OPERAND, new Integer(40));
operators.put("*", new Integer(30));
operators.put("/", new Integer(30));
operators.put("+", new Integer(20));
operators.put("-", new Integer(20));
operators.put(ReversePolish.CLOSEBRACKET, new Integer(0));
ReversePolish rp = new ReversePolish(operators);
List reversed = rp.parse2Polish(before);
System.out.print("Reversed:");
for (int i = 0; i < reversed.size(); i++) {
System.out.print(reversed.get(i));
}
System.out.println("");
この結果は、Reversed:12a*+ と表示されます。
| フィールドの概要 | |
static String |
CLOSEBRACKET
閉じカッコ")"です。 |
static String |
OPENPBRACKET
開きカッコ"("です。 |
static String |
OPERAND
オペランドを意味します。 |
| コンストラクタの概要 | |
ReversePolish()
デフォルトコンストラクタです。 |
|
ReversePolish(Map operatorPriority)
operatorPriorityで指定された演算子と優先順位を持つインスタンスを生成します。 |
|
| メソッドの概要 | |
List |
parse2Polish(List tokens)
tokensに設定された演算式を逆ポーランド記法に変換します。 |
void |
setOperator(Map operatorPriority)
演算子と優先順位を設定します。 |
| クラス java.lang.Object から継承したメソッド |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| フィールドの詳細 |
public static final String OPERAND
public static final String OPENPBRACKET
public static final String CLOSEBRACKET
| コンストラクタの詳細 |
public ReversePolish()
setOperator(Map)メソッドを必ず呼び出して下さい。
setOperator(Map)
public ReversePolish(Map operatorPriority)
throws IllegalArgumentException
operatorPriority - 演算子とその優先順位を設定したMap
IllegalArgumentException - operatorPriorityがnullの場合| メソッドの詳細 |
public void setOperator(Map operatorPriority)
throws IllegalArgumentException
operatorPriority - 演算子とその優先順位を設定したMap
IllegalArgumentException - operatorPriorityがnullの場合public List parse2Polish(List tokens)
tokens - オペランドまたは演算子を要素に持つリスト
|
|||||||||||
| 前のクラス 次のクラス | フレームあり フレームなし | ||||||||||
| 概要: 入れ子 | フィールド | コンストラクタ | メソッド | 詳細: フィールド | コンストラクタ | メソッド | ||||||||||