## 四则运算

1）除了整数以外，还要支持真分数的四则运算，例如：1/6+1/8=7/24
2）程序要求能处理用户的输入，判断对错，累积分数
3）程序支持可以由用户自行选择加、减、乘、除运算
4）使用-n参数控制生成题目的个数，例如Myapp.exe -n 10，将生成10个题目

public class FourFundamentalRules {
private static Stack stack = new Stack<>();//后缀表达式
private static Stack stack_1 = new Stack<>();//符号栈
private static Stack stack_2 = new Stack<>();//临时栈
public static void main(String[] args) {
String str = "1+(2-3/4)5";
try {
Double b = calculate(str);
System.out.println("运算结果为："+b);
}catch (Exception e){
System.out.println("error");
}
}
//运算
private static Double calculate(String str) throws Exception{
char[] arr = str.toCharArray();
//转化为后缀表达式
for(int i=0;i<arr.length;i++){
if(Character.isDigit(arr[i])){//判断是否为数字
stack.push(arr[i]);
}else if(arr[i] == '
'||arr[i] == '/'){
while(!stack_1.empty()){
char ch = stack_1.pop();
if(ch == '('){
stack_1.push(ch);
break;
}else if(ch == '' || ch == '/'){
stack.push(ch);
}else{
stack_2.push(ch);
}
}
while(!stack_2.empty()){
stack_1.push(stack_2.pop());
}
stack_1.push(arr[i]);
} else if(arr[i] == '+'|| arr[i] == '-'){
while(!stack_1.empty()){
char ch = stack_1.pop();
if(ch == '('){
stack_1.push(ch);
break;
}else if(ch == '
' || ch == '/'||ch == '+'|| ch == '-'){
stack.push(ch);
}else{
stack_2.push(ch);
}
}while(!stack_2.empty()){
stack_1.push(stack_2.pop());
}
stack_1.push(arr[i]);
}else if(arr[i] == '('){
stack_1.push(arr[i]);
}else if(arr[i] == ')'){
char ch = stack_1.peek();
while(ch != '('){
ch = stack_1.pop();
stack.push(ch);
}
stack.pop();
}else{
throw new Exception();
}
}
while(!stack_1.empty()){
stack.push(stack_1.pop());
}
//进行运算
while(!stack.empty()){
stack_2.push(stack.pop());
}
Stack s = new Stack<>();//用于最后计算的栈
while(!stack_2.empty()){
char ch = stack_2.pop();
if(ch == '' || ch == '/'||ch == '+'|| ch == '-'){
double sum = 0;
double num1= s.pop();
double num2= s.pop();
switch (ch){
case '
':sum = num2*num1;break;
case '/':sum = num2/num1;break;
case '+':sum = num2+num1;break;
case '-':sum = num2-num1;break;
}
s.push(sum);
}else if (Character.isDigit(ch)){
s.push((double)Character.getNumericValue(ch));
}else{
throw new Exception();
}
}
return s.pop();
}
}

posted on 2020-10-28 09:07  _从前  阅读(165)  评论(0编辑  收藏  举报