Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.BigDecimal;
- import java.text.DecimalFormat;
- import java.util.Scanner;
- public class _03_Problem3 {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- String expression = sc.nextLine().replaceAll(" ", "");
- double totalSum = 0;
- for(int i = 0; i < expression.length(); ) {
- int signPos = nextSignPossition(expression, 1);
- int nextSignPost = nextSignPossition(expression, signPos + 1);
- if(nextSignPost == -1) {
- double firstNumber = Double.parseDouble(expression.substring(0, signPos));
- String operation = expression.substring(signPos, signPos + 1);
- double secondNumber = Double.parseDouble(expression.substring(signPos + 1, expression.length()));
- totalSum = calc(firstNumber, secondNumber, operation);
- break;
- }
- double firstNumber = Double.parseDouble(expression.substring(0, signPos));
- String operation = expression.substring(signPos, signPos + 1);
- double secondNumber = Double.parseDouble(expression.substring(signPos + 1, nextSignPost));
- String sum = calc(firstNumber, secondNumber, operation) + "";
- expression = sum + expression.substring(nextSignPost);
- }
- }
- public static double calc(double firstValue, double secondValue, String sign) {
- double sum = 0;
- switch (sign) {
- case "+":
- sum = firstValue + secondValue;
- break;
- case "-":
- sum = firstValue - secondValue;
- break;
- default:
- break;
- }
- return sum;
- }
- public static int nextSignPossition (String expression, int start) {
- int signPos;
- int plusIndex = expression.indexOf("+", start);
- int minusIndex = expression.indexOf("-", start);
- if (plusIndex == -1 && minusIndex == -1) {
- signPos = -1;
- }
- else {
- signPos = (plusIndex < minusIndex && plusIndex != -1 || minusIndex == -1) ? plusIndex : minusIndex;
- }
- return signPos;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement