import java.util.ArrayList;
目前創(chuàng)新互聯(lián)公司已為千余家的企業(yè)提供了網(wǎng)站建設(shè)、域名、雅安服務(wù)器托管、網(wǎng)站托管、服務(wù)器租用、企業(yè)網(wǎng)站設(shè)計(jì)、東光網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶(hù)導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶(hù)和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
import java.util.Stack;
/**itjob
*
* @author yhh
*
*/
public class Calculate {
/**
* 將字符串轉(zhuǎn)化成List
* @param str
* @return
*/
public ArrayListString getStringList(String str){
ArrayListString result = new ArrayListString();
String num = "";
for (int i = 0; i str.length(); i++) {
if(Character.isDigit(str.charAt(i))){
num = num + str.charAt(i);
}else{
if(num != ""){
result.add(num);
}
result.add(str.charAt(i) + "");
num = "";
}
}
if(num != ""){
result.add(num);
}
return result;
}
/**
* 將中綴表達(dá)式轉(zhuǎn)化為后綴表達(dá)式
* @param inOrderList
* @return
*/
public ArrayListString getPostOrder(ArrayListString inOrderList){
ArrayListString result = new ArrayListString();
StackString stack = new StackString();
for (int i = 0; i inOrderList.size(); i++) {
if(Character.isDigit(inOrderList.get(i).charAt(0))){
result.add(inOrderList.get(i));
}else{
switch (inOrderList.get(i).charAt(0)) {
case '(':
stack.push(inOrderList.get(i));
break;
case ')':
while (!stack.peek().equals("(")) {
result.add(stack.pop());
}
stack.pop();
break;
default:
while (!stack.isEmpty() compare(stack.peek(), inOrderList.get(i))){
result.add(stack.pop());
}
stack.push(inOrderList.get(i));
break;
}
}
}
while(!stack.isEmpty()){
result.add(stack.pop());
}
return result;
}
/**
* 計(jì)算后綴表達(dá)式
* @param postOrder
* @return
*/
public Integer calculate(ArrayListString postOrder){
Stack stack = new Stack();
for (int i = 0; i postOrder.size(); i++) {
if(Character.isDigit(postOrder.get(i).charAt(0))){
stack.push(Integer.parseInt(postOrder.get(i)));
}else{
Integer back = (Integer)stack.pop();
Integer front = (Integer)stack.pop();
Integer res = 0;
switch (postOrder.get(i).charAt(0)) {
case '+':
res = front + back;
break;
case '-':
res = front - back;
break;
case '*':
res = front * back;
break;
case '/':
res = front / back;
break;
}
stack.push(res);
}
}
return (Integer)stack.pop();
}
/**
* 比較運(yùn)算符等級(jí)
* @param peek
* @param cur
* @return
*/
public static boolean compare(String peek, String cur){
if("*".equals(peek) ("/".equals(cur) || "*".equals(cur) ||"+".equals(cur) ||"-".equals(cur))){
return true;
}else if("/".equals(peek) ("/".equals(cur) || "*".equals(cur) ||"+".equals(cur) ||"-".equals(cur))){
return true;
}else if("+".equals(peek) ("+".equals(cur) || "-".equals(cur))){
return true;
}else if("-".equals(peek) ("+".equals(cur) || "-".equals(cur))){
return true;
}
return false;
}
public static void main(String[] args) {
Calculate calculate = new Calculate();
String s = "12+(23*3-56+7)*(2+90)/2";
ArrayList result = calculate.getStringList(s); //String轉(zhuǎn)換為L(zhǎng)ist
result = calculate.getPostOrder(result); //中綴變后綴
int i = calculate.calculate(result); //計(jì)算
System.out.println(i);
}
}
import java.util.Collections;
import java.util.Stack;
public class Calculator {
private StackString postfixStack = new StackString();//后綴式棧
private StackCharacter opStack = new StackCharacter();//運(yùn)算符棧
private int [] operatPriority = new int[] {0,3,2,1,-1,1,0,2};//運(yùn)用運(yùn)算符ASCII碼-40做索引的運(yùn)算符優(yōu)先級(jí)
public static void main(String[] args) {
System.out.println(5+12*(3+5)/7.0);
Calculator cal = new Calculator();
String s = "5+12*(3+5)/7";
double result = cal.calculate(s);
System.out.println(result);
}
/**
* 按照給定的表達(dá)式計(jì)算
* @param expression 要計(jì)算的表達(dá)式例如:5+12*(3+5)/7
* @return
*/
public double calculate(String expression) {
StackString resultStack = new StackString();
prepare(expression);
Collections.reverse(postfixStack);//將后綴式棧反轉(zhuǎn)
String firstValue ,secondValue,currentValue;//參與計(jì)算的第一個(gè)值,第二個(gè)值和算術(shù)運(yùn)算符
while(!postfixStack.isEmpty()) {
currentValue = postfixStack.pop();
if(!isOperator(currentValue.charAt(0))) {//如果不是運(yùn)算符則存入操作數(shù)棧中
resultStack.push(currentValue);
} else {//如果是運(yùn)算符則從操作數(shù)棧中取兩個(gè)值和該數(shù)值一起參與運(yùn)算
secondValue = resultStack.pop();
firstValue = resultStack.pop();
String tempResult = calculate(firstValue, secondValue, currentValue.charAt(0));
resultStack.push(tempResult);
}
}
return Double.valueOf(resultStack.pop());
}
/**
* 數(shù)據(jù)準(zhǔn)備階段將表達(dá)式轉(zhuǎn)換成為后綴式棧
* @param expression
*/
private void prepare(String expression) {
opStack.push(',');//運(yùn)算符放入棧底元素逗號(hào),此符號(hào)優(yōu)先級(jí)最低
char[] arr = expression.toCharArray();
int currentIndex = 0;//當(dāng)前字符的位置
int count = 0;//上次算術(shù)運(yùn)算符到本次算術(shù)運(yùn)算符的字符的長(zhǎng)度便于或者之間的數(shù)值
char currentOp ,peekOp;//當(dāng)前操作符和棧頂操作符
for(int i=0;iarr.length;i++) {
currentOp = arr[i];
if(isOperator(currentOp)) {//如果當(dāng)前字符是運(yùn)算符
if(count 0) {
postfixStack.push(new String(arr,currentIndex,count));//取兩個(gè)運(yùn)算符之間的數(shù)字
}
peekOp = opStack.peek();
if(currentOp == ')') {//遇到反括號(hào)則將運(yùn)算符棧中的元素移除到后綴式棧中直到遇到左括號(hào)
while(opStack.peek() != '(') {
postfixStack.push(String.valueOf(opStack.pop()));
}
opStack.pop();
} else {
while(currentOp != '(' peekOp != ',' compare(currentOp,peekOp) ) {
postfixStack.push(String.valueOf(opStack.pop()));
peekOp = opStack.peek();
}
opStack.push(currentOp);
}
count = 0;
currentIndex = i+1;
} else {
count++;
}
}
if(count 1 || (count == 1 !isOperator(arr[currentIndex]))) {//最后一個(gè)字符不是括號(hào)或者其他運(yùn)算符的則加入后綴式棧中
postfixStack.push(new String(arr,currentIndex,count));
}
while(opStack.peek() != ',') {
postfixStack.push(String.valueOf( opStack.pop()));//將操作符棧中的剩余的元素添加到后綴式棧中
}
}
/**
* 判斷是否為算術(shù)符號(hào)
* @param c
* @return
*/
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '(' ||c == ')';
}
/**
* 利用ASCII碼-40做下標(biāo)去算術(shù)符號(hào)優(yōu)先級(jí)
* @param cur
* @param peek
* @return
*/
public boolean compare(char cur,char peek) {// 如果是peek優(yōu)先級(jí)高于cur,返回true,默認(rèn)都是peek優(yōu)先級(jí)要低
boolean result = false;
if(operatPriority[(peek)-40] = operatPriority[(cur) - 40]) {
result = true;
}
return result;
}
/**
* 按照給定的算術(shù)運(yùn)算符做計(jì)算
* @param firstValue
* @param secondValue
* @param currentOp
* @return
*/
private String calculate(String firstValue,String secondValue,char currentOp) {
String result = "";
switch(currentOp) {
case '+':
result = String.valueOf(ArithHelper.add(firstValue, secondValue));
break;
case '-':
result = String.valueOf(ArithHelper.sub(firstValue, secondValue));
break;
case '*':
result = String.valueOf(ArithHelper.mul(firstValue, secondValue));
break;
case '/':
result = String.valueOf(ArithHelper.div(firstValue, secondValue));
break;
}
return result;
}
}
public class ArithHelper {
// 默認(rèn)除法運(yùn)算精度
private static final int DEF_DIV_SCALE = 16;
// 這個(gè)類(lèi)不能實(shí)例化
private ArithHelper() {
}
/**
* 提供精確的加法運(yùn)算。
*
* @param v1 被加數(shù)
* @param v2 加數(shù)
* @return 兩個(gè)參數(shù)的和
*/
public static double add(double v1, double v2) {
java.math.BigDecimal b1 = new java.math.BigDecimal(Double.toString(v1));
java.math.BigDecimal b2 = new java.math.BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
public static double add(String v1, String v2) {
java.math.BigDecimal b1 = new java.math.BigDecimal(v1);
java.math.BigDecimal b2 = new java.math.BigDecimal(v2);
return b1.add(b2).doubleValue();
}
/**
* 提供精確的減法運(yùn)算。
*
* @param v1 被減數(shù)
* @param v2 減數(shù)
* @return 兩個(gè)參數(shù)的差
*/
public static double sub(double v1, double v2) {
java.math.BigDecimal b1 = new java.math.BigDecimal(Double.toString(v1));
java.math.BigDecimal b2 = new java.math.BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
public static double sub(String v1, String v2) {
java.math.BigDecimal b1 = new java.math.BigDecimal(v1);
java.math.BigDecimal b2 = new java.math.BigDecimal(v2);
return b1.subtract(b2).doubleValue();
}
/**
* 提供精確的乘法運(yùn)算。
*
* @param v1
* 被乘數(shù)
* @param v2
* 乘數(shù)
* @return 兩個(gè)參數(shù)的積
*/
public static double mul(double v1, double v2) {
java.math.BigDecimal b1 = new java.math.BigDecimal(Double.toString(v1));
java.math.BigDecimal b2 = new java.math.BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
public static double mul(String v1, String v2) {
java.math.BigDecimal b1 = new java.math.BigDecimal(v1);
java.math.BigDecimal b2 = new java.math.BigDecimal(v2);
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相對(duì))精確的除法運(yùn)算,當(dāng)發(fā)生除不盡的情況時(shí),精確到 小數(shù)點(diǎn)以后10位,以后的數(shù)字四舍五入。
*
* @param v1
* 被除數(shù)
* @param v2
* 除數(shù)
* @return 兩個(gè)參數(shù)的商
*/
public static double div(double v1, double v2) {
return div(v1, v2, DEF_DIV_SCALE);
}
public static double div(String v1, String v2) {
java.math.BigDecimal b1 = new java.math.BigDecimal(v1);
java.math.BigDecimal b2 = new java.math.BigDecimal(v2);
return b1.divide(b2, DEF_DIV_SCALE, java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供(相對(duì))精確的除法運(yùn)算。當(dāng)發(fā)生除不盡的情況時(shí),由scale參數(shù)指 定精度,以后的數(shù)字四舍五入。
*
* @param v1 被除數(shù)
* @param v2 除數(shù)
* @param scale 表示表示需要精確到小數(shù)點(diǎn)以后幾位。
* @return 兩個(gè)參數(shù)的商
*/
public static double div(double v1, double v2, int scale) {
if (scale 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
java.math.BigDecimal b1 = new java.math.BigDecimal(Double.toString(v1));
java.math.BigDecimal b2 = new java.math.BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精確的小數(shù)位四舍五入處理。
*
* @param v 需要四舍五入的數(shù)字
* @param scale 小數(shù)點(diǎn)后保留幾位
* @return 四舍五入后的結(jié)果
*/
public static double round(double v, int scale) {
if (scale 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
java.math.BigDecimal b = new java.math.BigDecimal(Double.toString(v));
java.math.BigDecimal one = new java.math.BigDecimal("1");
return b.divide(one, scale, java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static double round(String v, int scale) {
if (scale 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
java.math.BigDecimal b = new java.math.BigDecimal(v);
java.math.BigDecimal one = new java.math.BigDecimal("1");
return b.divide(one, scale, java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
這個(gè)應(yīng)該是老師留的作業(yè)呵呵,我做過(guò)。不過(guò)現(xiàn)在沒(méi)有代碼了。現(xiàn)在想想當(dāng)時(shí)做的挺傻的,你完全可以自己去實(shí)現(xiàn)。多看一些io方面的東西。僅僅用字符串操作也可以。逐個(gè)字符判斷,當(dāng)判斷到你是操作符時(shí)候,再判斷是哪一個(gè)符號(hào),做相應(yīng)的加減乘除就可以了。
import java.util.Scanner;
import java.util.Stack;
public class 表達(dá)式計(jì)算 {
private static StackString num = new StackString();//存后綴表達(dá)式
private static StackString sign = new StackString();//存入符號(hào)
private static StackInteger result = new StackInteger();//放結(jié)果
public static void getGroup(String line){//講字符串轉(zhuǎn)換為后綴表達(dá)式
for(int i=0; iline.length(); i++){
char c = line.charAt(i);
if((int)c=48 (int)c=57){//當(dāng)遇到數(shù)字的時(shí)候,判斷是不是多位數(shù),然后在push進(jìn)num
int j = i+1;
while(jline.length() (line.charAt(j)=48 line.charAt(j)=57)){
j++;
}
num.push(line.substring(i, j));
i = j-1;
}else if(c == '('){//遇到左括號(hào)直接存進(jìn)num
sign.push(String.valueOf(c));
}else if(c == ')'){//遇到右括號(hào)從sign中pop棧頂元素push到num知道遇到'(',然后再pop掉'('
while(!sign.peek().equals("(")){
num.push(sign.pop());
}
sign.pop();
}else{
int n = 0;
if(!sign.empty()){//如果sign中沒(méi)有元素,直接令n = 0
n = getNum(sign.peek().charAt(0));
}
int m = getNum(c);
if(m = n){//如果當(dāng)前元素的運(yùn)算級(jí)別比棧頂元素運(yùn)算級(jí)別要高,就直接push進(jìn)sign
sign.push(String.valueOf(c));
}else{
while(m n){//如果當(dāng)前運(yùn)算運(yùn)算級(jí)別比sign棧頂元素運(yùn)算級(jí)別要低,就將sign棧頂元素pop并且push進(jìn)num,知道不符合條件
num.push(sign.pop());//輸入例子2*3+6/3的時(shí)候,這里一直報(bào)錯(cuò)
if(!sign.empty()){
n = getNum(sign.peek().charAt(0));
}else{
n = 0;
}
}
sign.push(String.valueOf(c));
}
}
}
while(!sign.empty()){
num.push(sign.pop());
}
}
private static int getNum(char c){
int n = 0;
switch(c){
case '+':
case '-':
n = 1;
break;
case '*':
case '/':
n = 2;
break;
}
return n;
}