Implementation hints
Every RPN
expression may be viewed as a sequence of tokens each having both a
type and a content. Consider the following expression -1.34 0.34
+ sqrt
consisting of four tokens:
Type: Double | Type: Double| Type: Binary plus | Type: square Function | | operator | root Value: -1.34 | Value: 0.34 | Value: + | value: sqrt
The following scanner application utilizes pattern
matching for decomposing expressions like -1.34 0.34 +
sqrt
into a token sequence:
final String[] patterns = new String[] {
"sqrt",
"[-]?([0-9]+[.]?[0-9]*|[.][0-9]+)(E[-]?[0-9]+)?",// Matches e.g. -1.5E-33
"\\+"};// Escape required avoiding regular expression syntax clash.
final String expression = "2.1 -3.4 sqrt";
try (final Scanner scanner = new Scanner(expression)) {
while (scanner.hasNext()) {
for (final String p: patterns) {
if (scanner.hasNext(p)) {
System.out.println("Token '" + scanner.next(p) +
"' matched by '" + p + "'");
break;
}
}
}
}
The current example expression -1.34 0.34 + sqrt
results in:
Token '2.1' matched by '[-]?([0-9]+[.]?[0-9]*|[.][0-9]+)(E[-]?[0-9]+)?' Token '-3.4' matched by '[-]?([0-9]+[.]?[0-9]*|[.][0-9]+)(E[-]?[0-9]+)?' Token 'sqrt' matched by 'sqrt'
We provide error handling capabilities dealing with erroneous input ❶:
...
final String[] patterns = new String[] {
"sqrt",
"[-]?([0-9]+[.]?[0-9]*|[.][0-9]+)(E[-]?[0-9]+)?",// Matches e.g. -1.5E-33
"\\+"};// Escape required avoiding regular expression syntax clash.
try (final Scanner scanner = new Scanner("2.1 -3.4 pbck") ❶) {
while (scanner.hasNext()) {
boolean foundToken = false;
for (final String p: patterns) {
if (scanner.hasNext(p)) {
foundToken = true;
System.out.println("Token '" + scanner.next(p) +
"' matched by '" + p + "'");
break;
}
}
if (!foundToken) {
System.out.println("Parsing error at '" + scanner.nextLine() + "'");
System.exit(1);
} ...
Bogus input like 2.1 -3.4 pbck
will now be detected as such:
Token '2.1' matched by '[-]?([0-9]+[.]?[0-9]*|[.][0-9]+)(E[-]?[0-9]+)?'
Token '-3.4' matched by '[-]?([0-9]+[.]?[0-9]*|[.][0-9]+)(E[-]?[0-9]+)?'
Parsing error at 'pbck'
A token sequence may then be evaluated using the postfix evaluation algorithm (Read it!).