问题
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?
回答1:
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]
[+, -, -, +, -]
回答2:
In your if
statement, you test if the char is a '-'
or a '+'
. Then, you parse the number that comes before. So you should parse the last number after your for
-loop finishes.
回答3:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Object o = engine.eval("12+23-42-53+4-31");
System.out.println(o);
来源:https://stackoverflow.com/questions/28500031/evaluating-a-math-expression-given-in-string