Advertisement
Filkolev

Simple Expression

May 23rd, 2015
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | None | 0 0
  1. import java.math.BigDecimal;
  2. import java.util.Scanner;
  3.  
  4. public class _03_SimpleExpression {
  5.     public static void main(String[] args) {
  6.         @SuppressWarnings("resource")
  7.         Scanner input = new Scanner(System.in);
  8.        
  9.         String initial = input.nextLine().replace(" ", "");
  10.        
  11.         String[] numbers = initial.split("(-)|(\\+)");
  12.         String[] operations = initial.split("[.\\d]+");
  13.        
  14.         int startIndex = 0;
  15.         if (operations[0] == "") {
  16.             startIndex++;
  17.         }
  18.        
  19.         BigDecimal sum = new BigDecimal(0);
  20.         char currentOperation = '+';
  21.        
  22.        
  23.         for (int j = 0; j < numbers.length; j++) {
  24.             BigDecimal num = new BigDecimal(numbers[j]);
  25.            
  26.             if (currentOperation == '+') {
  27.                 sum = sum.add(num);
  28.                
  29.             } else {
  30.                 sum = sum.subtract(num);
  31.             }
  32.            
  33.             startIndex++;
  34.            
  35.             if (startIndex <= operations.length - 1) {
  36.                 currentOperation = operations[startIndex].charAt(0);
  37.             }
  38.            
  39.         }
  40.  
  41.        
  42.         System.out.println(sum);               
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement