aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--calculator-javacc/Calculator.jj74
1 files changed, 59 insertions, 15 deletions
diff --git a/calculator-javacc/Calculator.jj b/calculator-javacc/Calculator.jj
index 6cc78f5..9222654 100644
--- a/calculator-javacc/Calculator.jj
+++ b/calculator-javacc/Calculator.jj
@@ -1,15 +1,36 @@
-options{DEBUG_PARSER = true; DEBUG_TOKEN_MANAGER = true;}
+options{
+ //DEBUG_PARSER = true; DEBUG_TOKEN_MANAGER = true;
+ STATIC=false;
+}
PARSER_BEGIN(Calculator)
+import java.util.Scanner;
+import java.io.StringReader;
+
public class Calculator {
- public static void main(String[] args) {
- try{
- Calculator parser = new Calculator(System.in);
- parser.Start();
- }catch (ParseException e){
- System.out.println(e.getMessage());
- }
- }
+
+ private static double currentNumber;
+
+ public static double fromString(String stringToParse) throws ParseException{
+ currentNumber = 0.0;
+
+ Calculator parser = new Calculator(new StringReader(stringToParse));
+ parser.parse();
+ return currentNumber;
+ }
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ while (true){
+ System.out.print("Type your expression: ");
+ String expression = scanner.nextLine();
+ try{
+ System.out.println("Returned: " + fromString(expression));
+ }catch (Throwable t){
+ System.out.println(t);
+ }
+ }
+ }
}
PARSER_END(Calculator)
@@ -22,14 +43,37 @@ SKIP : {
}
TOKEN : {
- <SPACE: " "|"\t">|
- <HELLO: "hello">|
- <WORLD: "world">|
- <HELLOWORLD: <HELLO> ( <SPACE> ) + <WORLD>>
+ <PAL: "(">|
+ <PAR: ")">|
+ <ADD: "+">|
+ <SUB: "-">|
+ <MUL: "*">|
+ <DIV: "/">|
+ <EQU: "=">|
+ <LET: "let">|
+ <END: "exit">|
+ <NUM: (["0"-"9"])+("."((["0"-"9"])+))?>|
+ <ID: (["a"-"z"]|["A"-"Z"])+>
+}
+
+
+
+double factor() :
+{
+ Token t;
+ double i;
+}
+{
+ t = <NUM>
+ {
+ i = Double.parseDouble(t.image);
+ currentNumber += i;
+ return i;
+ }
}
-void Start() : {
+void parse() : {
}
{
- (<HELLOWORLD>)* <EOF>
+ (factor())* <EOF>
} \ No newline at end of file