I need to write a code that takes a string input and turns it, or something to that effect, into a valid unary equation with addition to verify if it is valid. I'm confused, could anyone point me in the direction of understanding this?
An example would be:
111+1111=11111+1+1
is the statement 3+4=5+1+1
which is valid.
My other question would be how to use stacks to do unary operations.
If you are limited to this language then your can write a simple parser using a number of methods. You can first split your String
String[] parts = eqn.split("=");
Then split each part:
String[] left = parts[0].split("\\+");
String[] right = parts[1].split("\\+");
Now you can simply count the lengths of the strings:
int leftside = 0;
for (String l : left) {
leftside += l.length;
}
and so on for the right side and see if they are equal.
There are many other ways you can tackle this.
Basically you have to write a parser. You might want to use a character-by-character scanner, or use regexes or a generic tool such as ANTLR. It depends on your final goal and whether it is likely to change. Are you likely to have characters other than 1, +, =, for example?
My guess is this is homework. And I guess that you are expected to read character-by-character and push() each character on a stack. Then you have to pop() the stack when you encounter certain conditions.I'm not going to do this for you...