使用循环来读取数学表达式,分开数字

时间:2014-05-13 09:27:21

标签: java loops stack

我正在尝试使用堆栈结构将中缀转换为后缀表达式。有没有办法使用for循环从输入字符串中读取数字?

例如,如果输入是(23 + 9)* 2。我开发了一种方法来检查charAt(i)是+, - ,*还是/。我检查了第一个字符'''并将其推送到堆栈。然后我想将23作为一个数字读取,并将其添加到字符串后缀。If ( ! isOperator(charAt(i)),那么我该怎么办?我怎么能使用循环来做它?非常感谢!

for (int j=0;j<input.length();j++){
            char ch= input.charAt(j);             
            if(!isOperator){
                if (ch=='('){
                    s.push();

                }else{//if it's a number i.e.23, it should be attached to string post as 23, instead of 2 and 3, 

1 个答案:

答案 0 :(得分:1)

您可能需要StringBuilder来添加字符:

StringBuilder builder = new StringBuilder();
for (int j=0;j<input.length();j++){
  char ch= input.charAt(j);             
  if(!isOperator(ch)){
    if (ch=='('){
      // process contents of builder.toString(), if any, then reset builder
      s.push();
    } else {
      builder.append(ch);
    }
  } else {
    // process contents of builder.toString(), if any, then reset builder
  }