展开全部
public class houzhuibiaodashizi
{
public static void main(String[] args)
{
//中缀 => 后缀表达式
String s = "( 1.5*2+(20+10*2*10+44)/(12*11)-1)*2"; //中缀
System.out.println(s);
System.out.println(jisuan(s));
}
static double jisuan(String s)
{
String hs= ""; //后缀
char[] Operators = new char[s.length()];
int Top = -1;
for (int i = 0; i < s.length(); i++)
{
char C = s.charAt(i);
switch(C)
{
case ' ' : break;
case '+' : //操作符
case '-' :
while (Top >= 0) //栈不62616964757a686964616fe59b9ee7ad9431333262346561为空时
{
char c = Operators[Top--]; //pop Operator
if (c == '(')
{
Operators[++Top] = c; //push Operator
break;
}
else {hs = hs + c;}
}
Operators[++Top] = C; //push Operator
hs += " ";break;
case '*' : //操作符
case '/' :
while (Top >= 0) //栈不为空时
{
char c = Operators[Top--]; //pop Operator
if (c == '(')
{
Operators[++Top] = c; //push Operator
break;
}
else
{
if (c == '+' || c == '-')
{
Operators[++Top] = c; //push Operator
break;
}
else
{
hs = hs + c;
}
}
}
Operators[++Top] = C; //push Operator
hs += " ";
break;
case '(' : //操作符
Operators[++Top] = C;
hs+= " ";
break;
case ')' : //操作符
while (Top >= 0) //栈不为空时
{
char c = Operators[Top--]; //pop Operator
if (c == '(')
{
break;
}
else
{
hs= hs + c;
}
}
hs += " ";
break;
default : //操作数
hs= hs + C;
break;
}//switch
}/for
while (Top >= 0)
{
hs= hs + Operators[Top--]; //pop Operator
}
System.out.println("hs="+hs); //后缀
// 后缀
//后缀表达式计算
double[] Operands = new double[hs.length()];
double x, y, v;
Top = - 1;
String Operand = "";
for (int i = 0; i < hs.length(); i++)
{
char c = hs.charAt(i);
if ((c >= '0' && c <= '9') || c == '.')
{
Operand += c;
}
if ((c == ' ' && Operand != "") || i == hs.length() - 1)
{
Operands[++Top] = java.lang.Double.parseDouble(Operand) ; //push Operands
Operand = "";
}
if (c == '+' || c == '-' || c == '*' || c == '/')
{
if ((Operand != ""))
{
Operands[++Top] = java.lang.Double.parseDouble(Operand) ; //push Operands
Operand = "";
}
y = Operands[Top--]; //pop 双目运算符的第二操作数 (后进先出)注意操作数顺序对除法的影响
x = Operands[Top--]; //pop 双目运算符的第一操作数
switch (c)
{
case '+' :
v = x + y;
break;
case '-' :
v = x - y;
break;
case '*' :
v = x * y;
break;
case '/' :
v = x / y; // 第一操作数 / 第二操作数 注意操作数顺序对除法的影响
break;
default :
v = 0;
break;
}
Operands[++Top] = v; //push 中间结果再次入栈
}if
} ///for
v = Operands[Top--]; //pop 最终结果
System.out.println(v);
return v;
} /jisuan
}/houzhui/
已赞过
已踩过<
你对这个回答的评价是?
评论
收起
如果觉得《java用对话框输出计算结果_Java怎么实现输入一个string表达式然后输出计算的结果...》对你有帮助,请点赞、收藏,并留下你的观点哦!