Advertisement
Guest User

SimpleExpressionP3

a guest
Jun 2nd, 2014
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. import java.text.DecimalFormat;
  2. import java.text.NumberFormat;
  3. import java.util.Scanner;
  4.  
  5. import javax.script.ScriptEngine;
  6. import javax.script.ScriptEngineManager;
  7. import javax.script.ScriptException;
  8.  
  9. public class SimpleExpressionP3 {
  10.  
  11.     public static void main(String[] args) {
  12.         Scanner scan = new Scanner(System.in);
  13.         String input = scan.nextLine();
  14.         input = input.replaceAll("\\s+", "");
  15.         input = input.replaceAll("\\+", "+");
  16.         input = input.replaceAll("\\-", "-");
  17.        
  18.         String []nums = input.split("\\+|\\-");
  19.         String []operators = input.split("\\d+(\\.\\d{1,2})?|\\s+");
  20.         double a=0;
  21.        
  22.         double sum = Double.parseDouble((nums[0]));
  23.         for (int i = 1; i < nums.length; i++) {
  24.             a = Double.parseDouble(nums[i]);
  25.             if (operators[i].equals("+")) {
  26.                 sum+=a;
  27.                
  28.             }
  29.             else {
  30.                 sum-=a;
  31.             }
  32.            
  33.         }
  34.         NumberFormat formatter = new DecimalFormat("###.#########");  
  35.            
  36.         String f = formatter.format(sum);  
  37.         System.out.println(f);
  38.        
  39.  
  40.     }
  41.  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement