java具有优先级的计算器_带有优先级的计算器的优先级设置与实现(Java语言)

stk2 = new Stack();

for (int i = 0; i < s.length(); ++i){

char temp = s.charAt(i); // String 取其某一个元素

if ((temp >= '0' && temp <= '9') || temp == '.'){

double sum = temp - '0';

int j = i + 1;

boolean flag = true;

int index = 1;

while(j < s.length()){

temp = s.charAt(j);

if (temp == '.'){

flag = false;

index = 1;

++j;

continue;

}

else if (flag && (temp >= '0' && temp <= '9')){

sum = sum * 10 + temp - '0';

++j;

}else if (!flag && (temp >= '0' && temp <= '9')){

sum += Math.pow(0.1,index) * (temp - '0');

index ++;

++j;

}

else break;

}

System.out.println(sum);

stk1.push(new Double(sum));

i = j - 1;

}

else if (temp == '+' || temp == '-' || temp == '*' || temp == '/' || temp == '(' ){

if (stk2.empty() || get_out_priority(temp) >= get_in_priority(stk2.peek().charValue()))

stk2.push(new Character(temp));

else{

while(!stk2.empty() && (get_out_priority(temp) < get_in_priority(stk2.peek().charValue()))){

char c = stk2.peek().charValue();

stk2.pop();

double num2 = stk1.peek().doubleValue();

stk1.pop();

double num1 = stk1.peek().doubleValue();

stk1.pop();

if (c == '+') stk1.push(new Double(num1 + num2));

if (c == '-') stk1.push(new Double(num1 - num2));

if (c == '*') stk1.push(new Double(num1 * num2));

if (c == '/') stk1.push(new Double(num1 / num2));

}

stk2.push(new Character(temp));

}

}

else if (temp == ')'){ // ')'

while(stk2.peek().charValue() != '('){

char c = stk2.peek().charValue();

stk2.pop();

double num2 = stk1.peek().doubleValue();

stk1.pop();

double num1 = stk1.peek().doubleValue();

stk1.pop();

if (c == '+') stk1.push(new Double(num1 + num2));

if (c == '-') stk1.push(new Double(num1 - num2));

if (c == '*') stk1.push(new Double(num1 * num2));

if (c == '/') stk1.push(new Double(num1 / num2));

}

stk2.pop();

}

}

if (!stk2.empty()){

while(!stk2.empty()){

char c = stk2.peek().charValue();

stk2.pop();

double num2 = stk1.peek().doubleValue();

stk1.pop();

double num1 = stk1.peek().doubleValue();

stk1.pop();

if (c == '+') stk1.push(new Double(num1 + num2));

if (c == '-') stk1.push(new Double(num1 - num2));

if (c == '*') stk1.push(new Double(num1 * num2));

if (c == '/') stk1.push(new Double(num1 / num2));

}

}

text2.setText((stk1.peek().toString()));

System.out.println(stk1.peek().doubleValue());

}

int get_out_priority(char temp){

if (temp == '+') return 3;

if (temp == '-') return 3;

if (temp == '*') return 4;

if (temp == '/') return 4;

if (temp == '(') return 5;

return 0;

}

int get_in_priority(char temp){

if (temp == '+') return 3;

if (temp == '-') return 3;

if (temp == '*') return 4;

if (temp == '/') return 4;

if (temp == '(') return 0;

return 0;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值