四则运算

博客班级 https://edu.cnblogs.com/campus/ahgc/AHPU-SE-19

作业要求 https://edu.cnblogs.com/campus/ahgc/AHPU-SE-19/homework/11376

作业目标 四则运算题目生成程序

学号 3190704101
二.题目要求
写一个能自动生成小学四则运算题目的程序,然后在此基础上扩展:
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编辑  收藏  举报

导航