控制台版java 计算机 +=-/()

package com;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Calculator {
//+-*/()
public static void main(String[] args) {
// Pattern pattern = Pattern.compile("(?<=\\d)(\\+|-|\\*|/)");
// Matcher matcher = pattern.matcher("2-4");//3*((5*(2-4))*(3-1*2))
// while(matcher.find()){
// System.out.println(matcher.group());
// };
double rs = 0;
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
rs=count(str);
System.out.println(rs);
}
public static double count(String str){
Pattern p1 = Pattern.compile("\\([^\\(^\\)]*\\)");
Matcher m1 = p1.matcher(str);
if(m1.find()){
if(m1.start()==0&&m1.end()==str.length()){
if(str.startsWith("(")&&str.endsWith(")")){
str = str.substring(1,str.length()-1);
}
}
}
double rs = 0;
Pattern pattern = Pattern.compile("\\([^\\(^\\)]*\\)");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){//计算最里面的一对括号们
String str2 = matcher.group();
rs = count(str2);
str = str.replace(str2,String.valueOf(rs));
}
while(str.indexOf("(")>-1){//算完以后还有括号继续优先算
Matcher matcher2 = pattern.matcher(str);
while(matcher2.find()){
String str2 = matcher2.group();
rs = count(str2);
str = str.replace(str2,String.valueOf(rs));
}
} 
rs = count2(str);
return rs;
}
private static double count2(String str) {
if(str.startsWith("(")&&str.endsWith(")")){
str = str.substring(1,str.length()-1);
}
double rs = 0;
String[] nums = str.split("(?<=\\d)(\\+|-|\\*|/)");
String[] ctrls = str.replaceAll("[0-9.]|(?<!\\d)(\\+|-|\\*|/)", "").split("");
List<String> numsList = new ArrayList<String>();
List<String> ctrlsList = new ArrayList<String>();
for (String string : nums) {
numsList.add(string);
}
for (String string : ctrls) {
ctrlsList.add(string);
}
for (int i = 1; i < ctrlsList.size(); i++) {
if("*".equals(ctrlsList.get(i))||"/".equals(ctrlsList.get(i))){
double start = Double.parseDouble(numsList.get(i-1));
double end = Double.parseDouble(numsList.get(i));
if("*".equals(ctrlsList.get(i))){
rs = start*end;
}else{
rs = start/end;
}
ctrlsList.remove(i);
numsList.remove(i);
numsList.set(i-1, String.valueOf(rs));
i--;
}
}
for (int i = 1; i < ctrlsList.size(); i++) {
if("+".equals(ctrlsList.get(i))||"-".equals(ctrlsList.get(i))){
double start = Double.parseDouble(numsList.get(i-1));
double end = Double.parseDouble(numsList.get(i));
if("+".equals(ctrlsList.get(i))){
rs = start+end;
}else{
rs = start-end;
}
ctrlsList.remove(i);
numsList.remove(i);
numsList.set(i-1, String.valueOf(rs));
i--;
}
}
return rs;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值