Skip to content

Instantly share code, notes, and snippets.

@usharik
Created June 30, 2020 16:27
Show Gist options
  • Save usharik/2af3a573d0d61a710b8d53d6114694b3 to your computer and use it in GitHub Desktop.
Save usharik/2af3a573d0d61a710b8d53d6114694b3 to your computer and use it in GitHub Desktop.
package ru.geekbrains;
public class CalcApp {
private String[] tokens;
private int pos;
public CalcApp(String expr) {
this.tokens = expr.split(" ");
this.pos = 0;
}
/*
1+2+3-4+5
3+3-4+5
6-4+5
2+5
7
E -> T + E | T - E | T
T -> F + T | F - T | F
F -> -F1 | F1
F1 -> N | (E) | func(E)
*/
public static void main(String[] args) {
String expr = "1 + 2 * ( 3.0 / ( 2 + 7 ) - 4 ) / 5.0 + 10";
CalcApp calcApp = new CalcApp(expr);
System.out.println(calcApp.calculate());
System.out.println(1 + 2 * ( 3.0 / (2 + 7) - 4 ) / 5.0 + 10);
}
private double calculate() {
double first = multiply();
while (pos < tokens.length) {
String operator = tokens[pos];
if (!operator.equals("+") && !operator.equals("-")) {
break;
} else {
pos++;
}
double second = multiply();
if (operator.equals("+")) {
first += second;
} else {
first -= second;
}
}
return first;
}
public double multiply() {
double first = factor();
while (pos < tokens.length) {
String operator = tokens[pos];
if (!operator.equals("*") && !operator.equals("/")) {
break;
} else {
pos++;
}
double second = factor();
if (operator.equals("*")) {
first *= second;
} else {
first /= second;
}
}
return first;
}
public double factor() {
String next = tokens[pos];
double result;
if (next.equals("(")) {
pos++;
result = calculate();
String closingBracket;
if (pos < tokens.length) {
closingBracket = tokens[pos];
} else {
throw new IllegalArgumentException("Unexpected end of expression");
}
if (closingBracket.equals(")")) {
pos++;
return result;
}
throw new IllegalArgumentException("')' expected but " + closingBracket + " found");
}
pos++;
return Double.parseDouble(next);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment