Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.BigDecimal;
- import java.util.ArrayList;
- import java.util.Scanner;
- public class SimpleExpression {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- StringBuilder line = new StringBuilder(sc.nextLine());
- for (int i = 0; i < line.length(); i++) {
- if (line.charAt(i) == ' ') {
- line = line.deleteCharAt(i);
- i--;
- }
- }
- //System.out.println(line);
- BigDecimal result = BigDecimal.ZERO, lhs, rhs;
- String expr = line.toString();
- String[] operands = expr.split("[+-]");
- ArrayList<Character> signes = new ArrayList<>();
- for (int i = 0; i < expr.length(); i++) {
- if (expr.charAt(i) == '+' || expr.charAt(i) == '-') {
- signes.add(expr.charAt(i));
- }
- }
- //System.out.println(Arrays.asList(operands));
- //System.out.println(signes);
- if (operands[0].equals("")) {
- lhs = new BigDecimal(Double.parseDouble(operands[1]));
- if (signes.get(0) == '-') {
- lhs = lhs.negate();
- }
- for (int i = 1; i < operands.length - 1; i++) {
- rhs = new BigDecimal(Double.parseDouble(operands[i + 1]));
- if (signes.get(i) == '+') {
- result = lhs.add(rhs);
- }
- else {
- result = lhs.subtract(rhs);
- }
- lhs = result;
- }
- }
- else {
- lhs = new BigDecimal(Double.parseDouble(operands[0]));
- for (int i = 1; i < operands.length; i++) {
- rhs = new BigDecimal(Double.parseDouble(operands[i]));
- if (signes.get(i - 1) == '+') {
- result = lhs.add(rhs);
- }
- else {
- result = lhs.subtract(rhs);
- }
- lhs = result;
- }
- }
- System.out.printf("%.7f%n", result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement