集册 Java实例教程 获取反波兰表达式

获取反波兰表达式

欢马劈雪     最近更新时间:2020-01-02 10:19:05

423
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
获取反波兰表达式
// 来 自 时代Java - N o w  J a v a . c o m

//package com.nowjava;

import java.util.ArrayList;

import java.util.List;


import java.util.Stack;


public class Main {

    public static void main(String[] argv) throws Exception {

        String normalExpression = "nowjava.com";

        System.out.println(getInversePolandExpression(normalExpression));

    }


    static private List<String> getInversePolandExpression(
    /* 
    *来 自
     nowjava - 时代Java
    */

            String normalExpression) {

        List<String> inversePolandExpression = new ArrayList<String>();

        char[] normalChararray = (normalExpression + "$").toCharArray();

        // 

        Stack<String> signStack = new Stack<String>();

        List<Stack<String>> signStackList = new ArrayList<Stack<String>>();

        signStackList.add(signStack);

        // 

        int level = 0;


        int pointPosition = 0;

        double tempNumber = 0;

        boolean isInInteger = true;


        for (int i = 0; i < normalChararray.length; i++) {

            char tempChar = normalChararray[i];

            // 

            if (tempChar >= '0' && tempChar <= '9') {

                // 

                if (isInInteger) {

                    tempNumber = tempNumber * 10 + (int) (tempChar - 48);

                }

                // ?

                else {

                    tempNumber += (double) (tempChar - 48)

                            * Math.pow(0.1, i - pointPosition);

                }


            }

            // ?

            else if (tempChar == '.') {

                isInInteger = false;

                pointPosition = i;

            }

            // 

            else if (tempChar == '+' || tempChar == '-' || tempChar == '*'

                    || tempChar == '/' || tempChar == '$') {

                // 

                isInInteger = true;

                // ?

                if (tempNumber > 0) {

                    inversePolandExpression.add(String.valueOf(tempNumber));

                }

                // 0

                tempNumber = 0;

                // ???

                if ((tempChar == '+') || (tempChar == '-')

                        || tempChar == '$') {


                    while (!signStackList.get(level).isEmpty()) {

                        // 

                        inversePolandExpression.add(signStackList

                                .get(level).pop());

                    }

                }

                // ?


                signStackList.get(level).push(tempChar + "");


            } else if (tempChar == '(') {

                signStack = new Stack<String>();

                signStackList.add(signStack);

                level++;

            } else if (tempChar == 
展开阅读全文