评估字符串中给出的数学表达式 [英] Evaluating a math expression given in string

查看:212
本文介绍了评估字符串中给出的数学表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

  String test =12 + 23-42-53 + 4-31; 
int counter = 0;
堆栈<整数> numb = new Stack< Integer>();
堆栈< String> op = new Stack< String>(); (int i = 0; i< test.length(); i ++){
if(test.charAt(i)==' - '|| test.charAt(i)==' +'){
int number = Integer.parseInt(test.substring(counter,i));
counter = i + 1;
numb.push(number);
String oper = Character.toString(test.charAt(i));
op.push(oper);
}

}

如果我循环通过麻木堆栈测试字符串的最后一个数字丢失。有没有解决方案?

解决方案

当您退出for循环时,您不添加最后一个号码,因为没有更多您的测试字符串结尾处的 - 或+符号。



退出for循环后,只需将最后一个数字推入numb堆栈。 >

提示:计数器是最后一个数字开始的位置,最后一个位置是字符串长度。



如果你做正确打印堆栈:

  //打印堆栈以查看结果
System.out.println( numb.toString());
System.out.println(op.toString());

您将获得以下输出:

  [12,23,42,53,4,31] 
[+, - , - ,+, - ]
pre>

Here is my code:

String test = "12+23-42-53+4-31";
        int counter = 0;
        Stack<Integer> numb= new Stack<Integer>();
        Stack<String> op = new Stack<String>();
        for(int i = 0; i<test.length();i++){
            if(test.charAt(i)=='-' || test.charAt(i)=='+'){
                int number = Integer.parseInt(test.substring(counter, i));
                counter=i+1;
                numb.push(number);
                String oper = Character.toString(test.charAt(i));
                op.push(oper);
            }

        }

If I loop through numb stack then the last number of test string is missing. Are there any solutions?

解决方案

When you exit the for loop, you don't add the last number because there is no more "-" or "+" symbol at the end of your test String.

Just push the last number into the numb stack once you exit the for loop.

Hint: counter is the position where the last number starts, and the last position is the String length.

If you do it correct and print the stacks:

//Print the stacks to see result
System.out.println(numb.toString());
System.out.println(op.toString());

You will obtain following output:

[12, 23, 42, 53, 4, 31]
[+, -, -, +, -]

这篇关于评估字符串中给出的数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆