我正忙于为学校制作一个表达式树,我已经构建了正在制作树的部分,并且打印算术表达式的结果也可以。
有这个额外的部分来完成任务,我也想让它工作。额外的任务是使程序能够读取表达式。
我对这个很远,但我不确定我是否通过在 int 末尾放置数字以一种好的方式来编码这个东西。我要解决的问题是当有这样的表达式时...
(3*(8-2))+(12/4)
... 我如何从字符数组中取出 12他们是两个分开的角色?我在其余代码中使用了一个字符数组,但当然可以使用字符串来获取这两个字符。
我是这样做的:
// if the next character is a digit...
if (Character.isDigit(expression[i])) {
// ... make local variables 'nextNumber'...
int nextNumber = 0;
// ... and 'a' which already contains this first digit...
String a = Character.toString(expression[i]);
// ... so when we check for the next character...
for (int k = i+1; k < expression.length; k++) {
// ... wether it is a digit,...
if (Character.isDigit(expression[k])) {
// ... we can add that digit to 'a',...
a = a + Character.toString(expression[k]);
}
// ... and if it is not a digit...
else if (!Character.isDigit(expression[k])) {
// ... we will exit the for loop.
break;
}
}
// now we have to change the String to an integer...
nextNumber = Integer.getInteger(a);
// ... and then we are sure we have the whole number as it was ment to be
// in the given expression
return new ET(nextNumber);
}
但这似乎太草率了。我用谷歌搜索了很长时间,我发现的都是这种方式,但我无法想象没有更简单或至少不那么马虎的方式。你们知道更好的方法还是这是要走的路?
我构建的解决方案是解决表达式树问题的一种相对简单的方法,我可以解决更多问题,但我不想花更多的时间,只要我可以向老师展示我理解教训。它的课程是算法,所以它并不是真正关于学习 Java,我的意思是我不是在要求老师让我解决的问题的解决方案。
先感谢您!