当前位置:网站首页>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
边栏推荐
- 线性代数第三章-矩阵的初等变换与线性方程组
- Pytorch learning record (7): skills in processing data and training models
- String notes
- 治疗TensorFlow后遗症——简单例子记录torch.utils.data.dataset.Dataset重写时的图片维度问题
- Paper on Image Restoration - [red net, nips16] image restoration using very deep revolutionary encoder decoder networks wi
- The official website of UMI yarn create @ umijs / UMI app reports an error: the syntax of file name, directory name or volume label is incorrect
- Generate excel template (drop-down selection, multi-level linkage)
- Remedy after postfix becomes a spam transit station
- Unsupervised denoising - [tmi2022] ISCL: dependent self cooperative learning for unpaired image denoising
- Traitement des séquelles du flux de Tensor - exemple simple d'enregistrement de torche. Utils. Données. Dataset. Problème de dimension de l'image lors de la réécriture de l'ensemble de données
猜你喜欢
Class loading and classloader understanding
如何利用对比学习做无监督——[CVPR22]Deraining&[ECCV20]Image Translation
Pytorch学习记录(十一):数据增强、torchvision.transforms各函数讲解
Chapter 4 of line generation - linear correlation of vector systems
Pytorch学习记录(七):处理数据和训练模型的技巧
Filebrowser realizes private network disk
Pyqy5 learning (2): qmainwindow + QWidget + qlabel
A sharp tool to improve work efficiency
Fundamentals of in-depth learning -- a simple understanding of meta learning (from Li Hongyi's course notes)
Pytorch学习记录(五):反向传播+基于梯度的优化器(SGD,Adagrad,RMSporp,Adam)
随机推荐
PyQy5学习(三):QLineEdit+QTextEdit
线性代数第一章-行列式
RedHat realizes keyword search in specific text types under the directory and keyword search under VIM mode
PyQt5学习(一):布局管理+信号和槽关联+菜单栏与工具栏+打包资源包
List segmentation best practices
Development environment EAS login license modification
Ptorch learning record (XIII): recurrent neural network
MySQL best practices for creating tables
Programming record - picture rotation function SciPy ndimage. Simple use and effect observation of rotate()
Pytorch学习记录(七):处理数据和训练模型的技巧
Viewer: introduce MySQL date function
对比学习论文——[MoCo,CVPR2020]Momentum Contrast for Unsupervised Visual Representation Learning
Pytorch学习记录(十二):学习率衰减+正则化
Best practices for MySQL storage time
数字图像处理基础(冈萨雷斯)一
自動控制(韓敏版)
The user name and password of users in the domain accessing the samba server outside the domain are wrong
Configure domestic image accelerator for yarn
PyQy5学习(四):QAbstractButton+QRadioButton+QCheckBox
JSP syntax and JSTL tag