正在检测表达式字符串中的运算符和操作数错误



我一直在试图弄清楚如何检测正则中缀表达式中发生的错误。我想到的第一件事看起来是这样的。。。

String expression = "(12 * 12) + (12 * 9)";
int numOfDigits = 0;
int numOfOperators = 0;
boolean onDigit = false;
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (Character.isDigit(ch) && !onDigit) {
numOfDigits += 1;
onDigit = true;
} else if (ch == '+' || ch == '-' || ch == '/' || ch == '*') {
numOfOperators += 1;
onDigit = false;
} else if (Character.isWhitespace(ch)) {
onDigit = false;
}
}
if (numOfDigits - 1 != numOfOperators) {
System.out.println("Missing operand(s) or operator(s) in expression");
}

唯一的问题是,我无法检测表达式中错误的来源。在这一点上,我决定使用这样的东西,因为它可以检测字符串中错误的来源。我遇到的唯一问题是,如果字符串末尾有一个运算符,我就不知道如何让程序检测到并显示错误。如有任何帮助,我们将不胜感激。

for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (lastType.equalsIgnoreCase("") && (ch == '+' || ch == '-' || ch == '/' || ch == '*')) {
System.out.printf("Missing operand at: %dn", lastLocation + 1);
break;
}
if (Character.isDigit(ch)) {
if (!onDigit) {
if (lastType.equalsIgnoreCase("digit")) {
System.out.printf("Missing operator at: %dn", lastLocation + lenOfDigit);
break;
}
lastType = "Digit";
lastLocation = i + 1;
numOfDigits += 1;
onDigit = true;
}
lenOfDigit++;
} else if (ch == '+' || ch == '-' || ch == '/' || ch == '*') {
if (lastType.equalsIgnoreCase("operator")) {
System.out.printf("Missing operand at: %dn", lastLocation + 1);
break;
}
lastType = "Operator";
lastLocation = i + 1;
numOfOperators += 1;
onDigit = false;
lenOfDigit = 0;
} else if (Character.isWhitespace(ch)) {
onDigit = false;
}
}

您可以向后遍历字符串并找到第一个索引,其中Character.isDigit()true。然后同时找到字符是运算符的第一个索引。如果运算符的索引大于数字的索引,那么您已经发现了运算符是表达式中最后一个字符的差异。

编辑:

我假设你想检测一个表达式何时有一个后面没有任何数字的运算符。

例如:"(12 * 12) + (12 * 9) +"

你可以用检测到这一点

int lastDigitIndex = -1;
int lastOperatorIndex = -1;
for (int i = expression.length()-1; i >= 0; --i)
{
char ch = expression.charAt(i);
if (Character.isDigit(ch) && lastDigitIndex == -1)
lastDigitIndex = i;
else if((ch == '+' || ch == '-' || ch == '/' || ch == '*') && lastOperatorIndex == -1)
lastOperatorIndex = i;
if (lastDigitIndex != -1 && lastOperatorIndex != -1)
break;  
}
if (lastOperatorIndex > lastDigitIndex)
{
//Error found
}

最新更新