Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. ## Calculating Strings?

I'm working on an algorithm solving program, and I've ran into a slight problem, basically the outputted strings look something like this:
Equation = (1+1-2)+(2+2)
String 1 = 1+1-2
String 2 = 2+2

It basically cuts out the problems inside the brackets, and places them in a list(which will be used later to replace the problems with answers), so now I need to know how I can turn a string into a integer, and be able to use the symbols that put them together. Someone mentioned I should restructure the strings to look like this:
1 1 +
But I don't know how that could work.

Anyway, I need the strings turned into integers, and the signs readable so that I can read and check how these integers will be combined.

Thanks!

2. ## Re: Calculating Strings?

Search the web for info about postfix. You should find a algorithm to do it. Why should you change to postfix? Because it makes evaluation so much easier. 1 + 2 * 3 becomes 1 2 3 * +. Then you read the postfix expression. Each time you read an operand you push it onto a Stack. Each time you read an operator you pop 2 values off the Stack, perform operation and push result back onto Stack.

Push onto Stack
Push onto Stack
Push onto Stack
Pop 3
Pop 2
Multiply
Push 6 onto Stack
Pop 6
Pop 1
Push 7 onto Stack

Now you have finished reading the postfix expression and the result is the only value left on the Stack: 7.

If this is too much for you then I suggest attempting something simpler.

3. ## Re: Calculating Strings?

Originally Posted by Junky

Search the web for info about postfix. You should find a algorithm to do it. Why should you change to postfix? Because it makes evaluation so much easier. 1 + 2 * 3 becomes 1 2 3 * +. Then you read the postfix expression. Each time you read an operand you push it onto a Stack. Each time you read an operator you pop 2 values off the Stack, perform operation and push result back onto Stack.

Push onto Stack
Push onto Stack
Push onto Stack
Pop 3
Pop 2
Multiply
Push 6 onto Stack