Java 進行四則運算,java進行四則運算

來源:互聯網
上載者:User

Java 進行四則運算,java進行四則運算

四則運算的基礎原理是將中綴運算式轉換成為尾碼運算式。然後進行計算。

轉換思路和原理,可以參考將中綴運算式轉化為尾碼運算式


import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import java.util.Stack;import java.util.regex.Pattern;public class Arithmetic {//操作符stackprivate Stack<String> operator = new Stack<String>();//尾碼運算式private List<String> postFix = new ArrayList<String>();private Pattern operatorPattern = Pattern.compile("[\\d\\.]");private Pattern arithmeticPattern = Pattern.compile("[\\(\\)\\+\\-\\*\\/]");//將中綴運算式換為尾碼運算式public void parse(String s) {s = replace(s);int j = 0;for (int i = 0; i < s.length(); i++) {String temp = s.substring(i, i + 1);if (operatorPattern.matcher(temp).matches()) {continue;}if (arithmeticPattern.matcher(temp).matches()) {j = process(j, i, s, temp);} else if (" ".equals(temp)) {return;}}if (j < s.length()) {postFix.add(s.substring(j, s.length()));}while (!this.operator.isEmpty()) {postFix.add(operator.pop());}}private String replace(String s) {return s.replaceAll("\\s", "");}private int process(int startIndex, int currentIndex, String str, String word) {if (startIndex != currentIndex) {postFix.add(str.substring(startIndex, currentIndex));}addOperator(word);startIndex = currentIndex + 1;if (startIndex > str.length()) {startIndex = str.length();}return startIndex;}public void addOperator(String operator) {if ("(".equals(operator)) {} else if(")".equals(operator)) {while (!this.operator.isEmpty()) {String temp = this.operator.pop();if ("(".equals(temp)) {break;} else {postFix.add(temp);}}return;} else if (!this.operator.isEmpty()) {while(!this.operator.isEmpty()) {String temp = this.operator.peek();if (needPop(temp, operator)) {this.postFix.add(this.operator.pop());} else {break;}}}this.operator.add(operator);}public boolean needPop(String inStackTop, String current) {return getLevel(current.charAt(0)) <= getLevel(inStackTop.charAt(0));}public int getLevel(char operator) {switch (operator) {case '+':return 1;case '-':return 1;case '*':return 2;case '/':return 2;default:return -1;}}public BigDecimal compute() {Stack<BigDecimal> stack = new Stack<BigDecimal>(); for (int i=0; i < this.postFix.size(); i++) {if (arithmeticPattern.matcher(postFix.get(i)).matches()) {BigDecimal bd2 = stack.pop();BigDecimal bd1 = stack.pop();BigDecimal temp = compute(postFix.get(i).charAt(0), bd1, bd2);stack.add(temp);} else {stack.add(new BigDecimal(postFix.get(i)));}}return stack.pop();}private BigDecimal compute(char operator, BigDecimal bd1, BigDecimal bd2) {switch (operator) {case '+':return bd1.add(bd2);case '-':return bd1.subtract(bd2);case '*':return bd1.multiply(bd2);case '/':return bd1.divide(bd2);//應當使用bd1.divide(divisor, scale, roundingMode);default:return null;}}public static void main(String[] args) {Arithmetic arithmetic = new Arithmetic();arithmetic.parse("9+(3-1)*3+10/2");System.out.println(arithmetic.postFix);System.out.println(arithmetic.compute());arithmetic = new Arithmetic();arithmetic.parse("9+(3-1)*3+10/2+1000-200-(100+5-9/3)");System.out.println(arithmetic.postFix);System.out.println(arithmetic.compute());arithmetic = new Arithmetic();arithmetic.parse("9 + (3 - 1) * 3 + 10 / 2 + 1000 - 200 - ( 100 + 5 - 9 / 3)");System.out.println(arithmetic.postFix);System.out.println(arithmetic.compute());}}



java實現四則運算

最後一個提示沒看懂意思。import java.util.Random;
public class JiS {
public static void main(String[] args)
{
Random r=new Random();
char[]ch=new char[]{'+','-','*','/'};
boolean flag=true;
while(flag){
int a=r.nextInt(10001);
int b=r.nextInt(10001);
char c=ch[r.nextInt(ch.length)];
// System.out.println(a+","+b+","+c);
switch(c)
{
case '+':
if(a+b<=10000){System.out.println(a+"+"+b+"="+(a+b));flag=false;}
break;
case '-':
if(a-b>=0){System.out.println(a+"-"+b+"="+(a-b));flag=false;}
break;
case '*':
if(a*b<=10000){System.out.println(a+"*"+b+"="+a*b);flag=false;}
break;
case '/':
if(b!=0){System.out.println(a+"/"+b+"="+a/b);flag=false;}
break;
}
}
}
}
 
java實現四則運算

這裡計算要用到棧!
要是學過基礎的資料結構你應該知道怎麼計算!
其實挺挺複雜的!

棧讀取每一個數值和操作符
根據不同的優先順序進行計算!

給你推薦一個地址!看一下!
dev.csdn.net/article/54/54736.shtm
參考資料:dev.csdn.net/article/54/54736.shtm
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.