Skip to content

Commit 503ab90

Browse files
Add files via upload
1 parent ae9dcc7 commit 503ab90

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

examples/SimpleCalculator.java

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package examples;
2+
3+
import java.util.Scanner;
4+
5+
import org.ugp.serialx.Registry;
6+
import org.ugp.serialx.converters.DataParser;
7+
import org.ugp.serialx.converters.NumberConverter;
8+
import org.ugp.serialx.converters.OperationGroups;
9+
import org.ugp.serialx.converters.operators.ArithmeticOperators;
10+
11+
/**
12+
* This example will show you simple implementation of SerialX latest feature the recursive data parser!
13+
* In this example we will be creating simple evaluator of mathematical expressions!
14+
*
15+
* @author PETO
16+
*
17+
* @since 1.3.0
18+
*/
19+
public class SimpleCalculator
20+
{
21+
static Scanner scIn = new Scanner(System.in);
22+
23+
public static void main(String[] args)
24+
{
25+
/*
26+
* We could easily just use DataParser.REGISTRY but there is tone of stuff we do not need and it will just slow it down!
27+
*/
28+
Registry<DataParser> parsersRequiredToEvaluateMath = new Registry<>(new OperationGroups(), new ArithmeticOperators(), new NumberConverter());
29+
30+
/*
31+
* This is an example of simple custom parser this one will allow us to reuse answers of out previous evaluations!
32+
* We will access this old answer using 'ans' word!
33+
* Old ans must be provided as first one of args!
34+
*/
35+
DataParser ansParser = new DataParser()
36+
{
37+
@Override
38+
public Object parse(Registry<DataParser> myHomeRegistry, String str, Object... args)
39+
{
40+
if (str.equalsIgnoreCase("ans"))
41+
{
42+
if (args.length > 0)
43+
return args[0];
44+
return null;
45+
}
46+
return CONTINUE;
47+
}
48+
};
49+
parsersRequiredToEvaluateMath.add(ansParser);
50+
51+
Object oldAns = null;
52+
while (true)
53+
{
54+
System.out.print("Please insert your math problem: "); //Ask for input!
55+
String input = scIn.nextLine() ;//Read console input
56+
if (!(input = input.trim()).isEmpty()) //Avoiding empty input!
57+
{
58+
double t0 = System.nanoTime(); //Performing simple benchmark
59+
oldAns = DataParser.parseObj(parsersRequiredToEvaluateMath, input, oldAns); //Notice that we are inserting oldAns as compiler arguments for parseObj which are then picked up by our ansParser as well as every other registered DataParser.
60+
double t = System.nanoTime();
61+
62+
System.out.println(input + " = " + oldAns +"\n" + (t-t0)/1000000 + "ms \n"); //Parsing input!
63+
}
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)