第三次作业
import java.util.Stack;
public class Operate {
private Stack<Character> priStack = new Stack<Character>();
private Stack<Integer> numStack = new Stack<Integer>();;
public int caculate(String str) {
String temp;
StringBuffer tempNum = new StringBuffer();
StringBuffer string = new StringBuffer().append(str);
while (string.length() != 0) {
temp = string.substring(0, 1);
string.delete(0, 1);
if (!isNum(temp)) {
if (!"".equals(tempNum.toString())) {
int num = Integer.parseInt(tempNum.toString());
numStack.push(num);
tempNum.delete(0, tempNum.length());
}
while (ompare(temp.charAt(0)) && (!priStack.empty())) {
int a = (int) numStack.pop();
int b = (int) numStack.pop();
char ope = priStack.pop();
int result = 0;
switch (ope) {
case '+':
result = b + a;
numStack.push(result);
break;
case '-':
result = b - a;
numStack.push(result);
break;
case '*':
result = b * a;
numStack.push(result);
break;
case '/':
result = b / a;
numStack.push(result);
break;
}
}
if (temp.charAt(0) != '#') {
priStack.push(new Character(temp.charAt(0)));
if (temp.charAt(0) == ')') {
priStack.pop();
priStack.pop();
}
}
} else
tempNum = tempNum.append(temp);
}
return numStack.pop();
}
private boolean isNum(String temp) {
return temp.matches("[0-9]");
}
private boolean compare(char str) {
if (priStack.empty()) {
return true;
}
char last = (char) priStack.lastElement();
if (last == '(') {
return true;
}
switch (str) {
case '#':
return false;
case '(':
return true;
case ')':
return false;
case '*': {
if (last == '+' || last == '-')
return true;
else
return false;
}
case '/': {
if (last == '+' || last == '-')
return true;
else
return false;
}
case '+':
return false;
case '-':
return false;
}
return true;
}
public static void main(String args[]) {
Operate operate = new Operate(); int t = operate.caculate("(46+12=58
System.out.println(t);
}
}
结对编程两人合作完成任务。代码完整充分体现合作重要性。
合作编程是一件很有趣的事情,通过这次合作我明白了实现共同目标的重要性。我的编程小伙伴: 王迪 博客名: 向日葵luck 我的博客名:lmxhappy

浙公网安备 33010602011771号