Advertisement
aslv

Simple Expression

Jun 2nd, 2014
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. import java.math.BigDecimal;
  2. import java.util.ArrayList;
  3. import java.util.Scanner;
  4.  
  5.  
  6. public class SimpleExpression {
  7.  
  8.     public static void main(String[] args) {
  9.         Scanner sc = new Scanner(System.in);
  10.         StringBuilder line = new StringBuilder(sc.nextLine());
  11.         for (int i = 0; i < line.length(); i++) {
  12.             if (line.charAt(i) == ' ') {
  13.                 line = line.deleteCharAt(i);
  14.                 i--;
  15.             }
  16.         }
  17.         //System.out.println(line);
  18.         BigDecimal result = BigDecimal.ZERO, lhs, rhs;
  19.         String expr = line.toString();
  20.         String[] operands = expr.split("[+-]");
  21.         ArrayList<Character> signes = new ArrayList<>();
  22.         for (int i = 0; i < expr.length(); i++) {
  23.             if (expr.charAt(i) == '+' || expr.charAt(i) == '-') {
  24.                 signes.add(expr.charAt(i));
  25.             }
  26.         }
  27.  
  28.         //System.out.println(Arrays.asList(operands));
  29.         //System.out.println(signes);
  30.        
  31.         if (operands[0].equals("")) {
  32.             lhs = new BigDecimal(Double.parseDouble(operands[1]));
  33.             if (signes.get(0) == '-') {
  34.                 lhs = lhs.negate();
  35.             }
  36.             for (int i = 1; i < operands.length - 1; i++) {
  37.                 rhs = new BigDecimal(Double.parseDouble(operands[i + 1]));
  38.                 if (signes.get(i) == '+') {
  39.                     result = lhs.add(rhs);
  40.                 }
  41.                 else {
  42.                     result = lhs.subtract(rhs);
  43.                 }
  44.                 lhs = result;
  45.             }
  46.         }
  47.         else {
  48.             lhs = new BigDecimal(Double.parseDouble(operands[0]));
  49.             for (int i = 1; i < operands.length; i++) {
  50.                 rhs = new BigDecimal(Double.parseDouble(operands[i]));
  51.                 if (signes.get(i - 1) == '+') {
  52.                     result = lhs.add(rhs);
  53.                 }
  54.                 else {
  55.                     result = lhs.subtract(rhs);
  56.                 }
  57.                 lhs = result;
  58.             }
  59.         }
  60.         System.out.printf("%.7f%n", result);
  61.  
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement