java寫的專門對付運算式子的方法

來源:互聯網
上載者:User

標籤:

就是把昨天寫的寫成了爪哇,少了一些功能,基本的在,牛逼的大牛可以拿去修改做的更好。

public  boolean judge(char ch)//判斷是不是字元數字{if(ch >= '0' && ch <= '9'){return true;}return false;}public  String[] tochange(String s_1)//中綴運算式轉換為尾碼運算式{        String S[] = new String[1000];        StringBuffer numBuffer = new StringBuffer();        Stack<String> s = new Stack<String>();        int i = 0, j = 0;        char ch;        while(i != s_1.length())        {        ch = s_1.charAt(i);        if(ch >= '0' && ch <= '9')        {                while (judge(ch))                {                    numBuffer.append(ch);                    ch = s_1.charAt(++i);                }                S[j++] = numBuffer.toString();                numBuffer = new StringBuffer();                 continue;         }        else if(ch == '(')        {        s.push("(");        }        else if(ch == ')')        {        while(s.peek() != "(")        {        S[j++] = s.pop();        }        s.pop();        }        else if(ch == '+' || ch == '-')        {        while(s.size() != 0 && s.peek() != "(")        {        S[j++] = s.pop();        }                s.push(String.valueOf(ch));        }        else if(ch == '*' || ch == '/')        {        while(s.size() != 0 && (s.peek()== "*" || s.peek() == "/"))        {        S[j++] = s.pop();        }        s.push(String.valueOf(ch));        }        i++;        }                while (s.size() != 0)            S[j++] = s.pop();        S[j] = "=";            return S;}public int add(String s_1)//進行計算{String []sn = tochange(s_1);Stack<String>s = new Stack<String>();int i = 0,n = 0,m = 0,x = 0;char ch;while(sn[i] != "="){ch = sn[i].charAt(0);if(ch >= '0' && ch <= '9'){s.push(String.valueOf(sn[i]));}else if(ch == '+'){    n = Integer.parseInt(s.pop());m = Integer.parseInt(s.pop());    x = n + m;s.push(String.valueOf(x));}else if(ch == '-'){n = Integer.parseInt(s.pop());m = Integer.parseInt(s.pop());x = m - n;s.push(String.valueOf(x));}else if(ch == '*'){n = Integer.parseInt(s.pop());m = Integer.parseInt(s.pop());x = m * n;s.push(String.valueOf(x));}else if(ch == '/'){n = Integer.parseInt(s.pop());m = Integer.parseInt(s.pop());x = m / n;s.push(String.valueOf(x));}i++;}String ss = s.pop();int number = Integer.parseInt(ss);return number;}



java寫的專門對付運算式子的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.