📄 expression1.java
字号:
//此程序可以实现多位数的四则运算,只要在运行时例如:java Expression1 (12+23)*2/3
import ds_java.Stack1; //顺序存储结构的栈,数据元素类型为Obeject
import ds_java.Stack2;
public class Expression1 //链式存储结构的栈,数据元素类型为int
{
String expstr="";
String pstr="";
public Expression1(String str)
{
expstr=str; //构造方法以字符串str构造表达式对象,
}
public static void main(String args[])
{
String str="((1+2)*(3-4)+5-6)*(7/7)";
if(args.length>0)
str=args[0]; //获得表达式字符串
Expression1 exp1=new Expression1(str);
System.out.println("中缀表达式为: "+exp1.expstr);
System.out.println("后缀表达式为: "+exp1.postfix());
System.out.println("计算结果为: "+exp1.value());
}
public String postfix()
{
Stack1 s1=new Stack1(30); //创建空栈
char ch;
String out;
int i=0;
while(i<expstr.length())
{
ch=expstr.charAt(i); //将栈中数据元素类型转化为字符型
switch(ch)
{
case '+': //遇到+、-时
case '-':
while(!s1.isEmpty()&&!(s1.get()).equals("("))
{
out=(String)s1.pop();
pstr+=out;
}
s1.push(ch+"");
i++;
break;
case '*': //遇到*、\时
case '/':
while(!s1.isEmpty() && ((s1.get()).equals("*") || (s1.get()).equals("/")))
{
out=(String)s1.pop();
pstr+=out;
}
s1.push(ch+"");
i++;
break;
case '(': s1.push(ch+""); //遇到(时,入栈
i++;
break;
case ')': out=(String)s1.pop(); //遇到)时,出栈
while(!s1.isEmpty()&&(out==null || !out.equals("(")))
{
pstr+=out;
out=(String)s1.pop();
}
i++;
break;
default: while(ch>='0' && ch<='9') //遇到数字时
{
pstr+=ch;
i++;
if(i<expstr.length())
ch=expstr.charAt(i);
else
ch='=';
}
pstr+=" ";
break;
}
}
while(!s1.isEmpty())
{
out=(String)s1.pop();
pstr=pstr+out;
}
return pstr;
}
public int value()
{
Stack2 s2=new Stack2(); //创建空栈
char ch;
int i=0,x,y,z=0;
while(i<pstr.length())
{
ch=pstr.charAt(i); //将栈中某一位置数据元素类型转化为字符型并赋给ch
if(ch>'0' && ch<='9')
{
z=0;
while(ch!=' ')
{
z=z*10+Integer.parseInt(ch+""); //此语句可以获得后缀表达式的数字
i++;
ch=pstr.charAt(i);
}
i++;
s2.push(z);
}
else
{
y=s2.pop();
x=s2.pop();
switch(ch)
{
case '+': z=x+y;break;
case '-': z=x-y;break;
case '*': z=x*y;break;
case '/': z=x/y;break;
}
s2.push(z);
i++;
}
}
return s2.pop();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -