|
1 | 1 | package net.marcellperger.mathexpr.interactive; |
2 | 2 |
|
| 3 | +import net.marcellperger.mathexpr.MathSymbol; |
| 4 | +import net.marcellperger.mathexpr.parser.ExprParseException; |
| 5 | +import net.marcellperger.mathexpr.parser.Parser; |
| 6 | +import net.marcellperger.mathexpr.util.Input; |
| 7 | +import net.marcellperger.mathexpr.util.MathUtil; |
| 8 | +import org.jetbrains.annotations.NotNull; |
| 9 | +import org.jetbrains.annotations.Nullable; |
| 10 | + |
| 11 | +import java.io.PrintStream; |
3 | 12 | import java.util.Arrays; |
4 | 13 |
|
5 | 14 | import static net.marcellperger.mathexpr.util.Input.input; |
6 | 15 |
|
7 | 16 | public class Shell { |
| 17 | + Input in; |
| 18 | + PrintStream out; |
| 19 | + |
| 20 | + public Shell() { |
| 21 | + in = new Input(); |
| 22 | + out = System.out; |
| 23 | + } |
| 24 | + |
8 | 25 | public static void main(String[] args) { |
9 | | - System.out.println("args = " + Arrays.toString(args)); |
10 | | - System.out.print("Enter something: "); |
11 | | - System.out.println("You entered " + input()); |
| 26 | + new Shell().run(); |
| 27 | + } |
| 28 | + |
| 29 | + // TODO run() until exit better - parse exit command/Ctrl+C |
| 30 | + // TODO fails badly with unchecked exception on parsing `12 + (` |
| 31 | + |
| 32 | + public void run() { |
| 33 | + //noinspection InfiniteLoopStatement |
| 34 | + while (true) getAndRunCommand(); |
| 35 | + } |
| 36 | + |
| 37 | + public void getAndRunCommand() { |
| 38 | + runCommand(in.getInput(">? ")); |
| 39 | + } |
| 40 | + public void runCommand(String cmd) { |
| 41 | + @Nullable MathSymbol sym = parseCmdOrPrintError(cmd); |
| 42 | + if(sym == null) return; |
| 43 | + double value = sym.calculateValue(); |
| 44 | + out.println(MathUtil.roundToSigFigs(value, 10)); |
| 45 | + } |
| 46 | + public @Nullable MathSymbol parseCmdOrPrintError(String cmd) { |
| 47 | + // No special commands so pass straight to parser |
| 48 | + Parser p = new Parser(cmd); |
| 49 | + try { |
| 50 | + return p.parse(); |
| 51 | + } catch (ExprParseException exc) { |
| 52 | + out.println(exc); |
| 53 | + return null; |
| 54 | + } |
12 | 55 | } |
13 | 56 | } |
0 commit comments