当前位置:网站首页>Calculation (enter the calculation formula to get the result)
Calculation (enter the calculation formula to get the result)
2022-04-23 06:08:00 【linsa_ pursuer】
package com;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
public class Calculate {
public static void main(String[] args) throws Exception{
System.out.println(getResult("-2+3*5"));
}
private static String getResult(String formula) throws Exception{
formula = formula.replace("(","(");
formula = formula.replace(")",")");
String reg = "[0-9\\\\.*%+()/-]*";
if(!formula.matches(reg)){
return "";
}
int leftCount = 0;
int rightCount = 0;
for(int i=0;i<formula.length();i++){
int left = formula.indexOf("(",i);
if(left!=-1){
leftCount++;
i = left;
}else{
break;
}
}
for(int i=0;i<formula.length();i++){
int right = formula.indexOf(")",i);
if(right!=-1){
rightCount++;
i = right;
}else{
break;
}
}
if(leftCount!=rightCount){
return "";
}
String formulaResult = formula;
formulaResult = getBrackets(formulaResult);
formulaResult = formulaResult.replace(formulaResult, getResultDetail(formulaResult));
return new BigDecimal(formulaResult).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
}
// Handle expression parentheses
public static String getBrackets(String formula) throws Exception{
if(formula.contains("(")){
int left = formula.lastIndexOf("(");
int right = formula.indexOf(")",left);
String formulaTemp = formula.substring(left,right+1);
String result = getResultDetail(formulaTemp);
formula = formula.replace(formulaTemp,result);
formula = getBrackets(formula);
}
return formula;
}
// Calculation expression
public static String getResultDetail(String formula) throws Exception{
formula = formula.replace("(","");
formula = formula.replace(")","");
// Processing percentage
List<Integer> percentList = new LinkedList<Integer>();
for(int i=0;i<formula.length();i++){
int percent = formula.indexOf("%",i);
if(percent!=-1){
percentList.add(percent);
i=percent;
}else{
break;
}
}
String formulaTemp = formula;
for(int i=0;i<percentList.size();i++){
String percentNum = formula.substring(0,percentList.get(i));
int sub = percentNum.lastIndexOf("-");
int add = percentNum.lastIndexOf("+");
int mul = percentNum.lastIndexOf("*");
int div = percentNum.lastIndexOf("/");
int num = Integer.max(Integer.max(Integer.max(sub,add),mul),div);
String numStr = formula.substring(num+1,percentList.get(i));
formulaTemp = formulaTemp.replace(numStr+"%",new BigDecimal(numStr).multiply(
new BigDecimal("0.01")).setScale(4,BigDecimal.ROUND_HALF_UP).toString());
}
formula = formulaTemp;
String formulaResult = formula;
formulaResult = calculateFirst(formulaResult);
formulaResult = calculateSecond(formulaResult);
return formulaResult;
}
// Calculate all multipliers and divisions of the expression
public static String calculateFirst(String formula) throws Exception{
if(hasFirst(formula)){
formula = getFirst(formula);
formula = calculateFirst(formula);
}
return formula;
}
// Evaluate all additions and subtractions of the expression
public static String calculateSecond(String formula) throws Exception{
if(hasSecond(formula)){
formula = getSecond(formula);
formula = calculateSecond(formula);
}
return formula;
}
// Determine whether the expression has multiplication and division
public static boolean hasFirst(String formula) throws Exception{
int mul = formula.indexOf("*");
int div = formula.indexOf("/");
int max = Integer.max(mul,div);
boolean flag = false;
if(max != -1){
flag = true;
}
return flag;
}
// Judge whether the expression has addition and subtraction
public static boolean hasSecond(String formula) throws Exception{
int sub = formula.indexOf("-")==0?formula.indexOf("-",1):formula.indexOf("-");
int add = formula.indexOf("+");
int max = Integer.max(sub,add);
boolean flag = false;
if(max != -1){
flag = true;
}
return flag;
}
// Calculate expression multiplication and division , Return the following expression
public static String getFirst(String formula) throws Exception{
int mul = formula.indexOf("*");
int div = formula.indexOf("/");
int min = Integer.min(mul,div);
min = min==-1?Integer.max(mul,div):min;
String formulaResult = formula;
List<String > list = getFormula(formula,min);
BigDecimal result = bigDecimalCal(new BigDecimal(list.get(1)),new BigDecimal(list.get(2)),list.get(0).charAt(0));
formulaResult = formulaResult.replace(list.get(1) + list.get(0) + list.get(2), result.toString());
return formulaResult;
}
// Calculate the addition and subtraction of the expression , Return the following expression
public static String getSecond(String formula) throws Exception{
int sub = formula.indexOf("-")==0?formula.indexOf("-",1):formula.indexOf("-");
int add = formula.indexOf("+");
int min = Integer.min(sub,add);
min = min==-1?Integer.max(sub,add):min;
String formulaResult = formula;
List<String > list = getFormula(formula,min);
BigDecimal result = bigDecimalCal(new BigDecimal(list.get(1)),new BigDecimal(list.get(2)),list.get(0).charAt(0));
formulaResult = formulaResult.replace(list.get(1) + list.get(0) + list.get(2), result.toString());
return formulaResult;
}
// Find two parameters and operators
public static List<String> getFormula(String formula, int n) throws Exception{
List<String> list = new LinkedList<String>();
list.add(formula.charAt(n) + "");
String leftStr = formula.substring(0,n);
String rightStr = formula.substring(n+1);
int leftSub = leftStr.lastIndexOf("-");
int leftAdd = leftStr.lastIndexOf("+");
int leftMul = leftStr.lastIndexOf("*");
int leftDiv = leftStr.lastIndexOf("/");
int leftNum = Integer.max(Integer.max(Integer.max(leftSub,leftAdd),leftMul),leftDiv);
list.add(formula.substring(leftNum==0?leftNum:leftNum+1,n));
int rightSub = rightStr.lastIndexOf("-")==0?rightStr.indexOf("-",1):rightStr.indexOf("-");
int rightAdd = rightStr.lastIndexOf("+");
int rightMul = rightStr.lastIndexOf("*");
int rightDiv = rightStr.lastIndexOf("/");
int rightNum = -1;
List<Integer> rightList = new LinkedList<Integer>();
if(rightSub!=-1){
rightList.add(rightSub);
}
if(rightAdd!=-1){
rightList.add(rightAdd);
}
if(rightMul!=-1){
rightList.add(rightMul);
}
if(rightDiv!=-1){
rightList.add(rightDiv);
}
for(int i=0;i<rightList.size();i++){
if(rightNum == -1){
rightNum = rightList.get(i);
}else if(rightList.get(i)<rightNum){
rightNum = rightList.get(i);
}
}
list.add(formula.substring(n+1,rightNum == -1?formula.length():n+1+rightNum));
return list;
}
// Calculate and formulate two parameters and operators
public static BigDecimal bigDecimalCal(BigDecimal a1, BigDecimal a2, char operator) throws Exception{
switch (operator){
case '+':
return a1.add(a2);
case '-':
return a1.subtract(a2);
case '*':
return a1.multiply(a2);
case '/':
return a1.divide(a2,20,BigDecimal.ROUND_HALF_UP);
default:
break;
}
throw new Exception("illegal operator!");
}
}
版权声明
本文为[linsa_ pursuer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220533259540.html
边栏推荐
- Exception handling: grab and throw model
- On traversal of binary tree
- RPC must know and know
- Paper on Image Restoration - [red net, nips16] image restoration using very deep revolutionary encoder decoder networks wi
- 对比学习论文——[MoCo,CVPR2020]Momentum Contrast for Unsupervised Visual Representation Learning
- Dva中在effects中获取state的值
- Problems and solutions of database migration
- 去噪论文阅读——[CVPR2022]Blind2Unblind: Self-Supervised Image Denoising with Visible Blind Spots
- Pytorch learning record (V): back propagation + gradient based optimizer (SGD, adagrad, rmsporp, Adam)
- Opensips (1) -- detailed process of installing opensips
猜你喜欢
PyQt5学习(一):布局管理+信号和槽关联+菜单栏与工具栏+打包资源包
Anaconda
Pytorch学习记录(十一):数据增强、torchvision.transforms各函数讲解
线代第四章-向量组的线性相关
CONDA virtual environment management (create, delete, clone, rename, export and import)
Fundamentals of in-depth learning -- a simple understanding of meta learning (from Li Hongyi's course notes)
LDCT图像重建论文——Eformer: Edge Enhancement based Transformer for Medical Image Denoising
去噪论文阅读——[CVPR2022]Blind2Unblind: Self-Supervised Image Denoising with Visible Blind Spots
Anaconda安装PyQt5 和 pyqt5-tools后没有出现designer.exe的问题解决
Programming record - picture rotation function SciPy ndimage. Simple use and effect observation of rotate()
随机推荐
Viewer: introduce MySQL date function
Create binary tree
Font shape `OMX/cmex/m/n‘ in size <10.53937> not available (Font) size <10.95> substituted.
Opensips (1) -- detailed process of installing opensips
线性代数第三章-矩阵的初等变换与线性方程组
Pytorch notes - observe dataloader & build lenet with torch to process cifar-10 complete code
Kibana search syntax
Shansi Valley P290 polymorphism exercise
线代第四章-向量组的线性相关
Illustrate the significance of hashcode
Pytorch学习记录(四):参数初始化
In depth understanding of the relationship between dncblevel and noise denoising in the paper
umi官网yarn create @umijs/umi-app 报错:文件名、目录名或卷标语法不正确
Pytorch notes - get familiar with the network construction method by building RESNET (complete code)
CONDA virtual environment management (create, delete, clone, rename, export and import)
Pyqy5 learning (2): qmainwindow + QWidget + qlabel
Unsupervised denoising - [tmi2022] ISCL: dependent self cooperative learning for unpaired image denoising
Ptorch learning record (XIII): recurrent neural network
Graphic numpy array matrix
A sharp tool to improve work efficiency