# Parenthetical input

• January 17th, 2011, 08:22 PM
drax325
Parenthetical input
Hi, I still sort of a beginner (self taught) and I want to jump into a project that is covers things I'm not used to.

What I really want to do is deal with logical equation like ~(a&b), but my problem works the same for parenthetical math equations, so we can work on that.

I want the user to enter an equation with form like: (3*(2 +4)) allowing spaces and (,),[,]. Pretty much any math expression that makes use of parenthesis. I also want to be able to make a char[] or string[] e.g.= {3,2,4}.
It would be bonus if I could have the program deal with the input in the same way as a IDE shows if there are errors as you type.

So I have figured that there are many ways to do it, but the methods I know should work are long, tedious, and inefficient program.

I don't know if I should just turn the scanner into a string. And then work from the string.
I think working straight from the scanner might be better because it has next() type of methods, but I don't how to use. And I don't understand the whitespace, or using pattern if it could help.

Working from string: I've figured out how to remove the ( ) and spaces using replace() and replaceAll().
Why does equation = equation.replace( "(", "" ); but not equation = equation.replaceAll( "(", "" );

One method I thought of to remove just the letters from the string and put into the array. I would have to create a if statement for every letter. Which i don't want to write 52 if statements. This all of what my problem is I have to deal with long for loops and tedious if statements. I want to learn easier ways.

I created a method to count left parenthesis and right parenthesis. If they are not equal it allows the equation not run and report error. The number from the parenthesis I think will help go through order of the operations. But, all the things I have talked about doesn't get close to actually apply the operations.
My plan is to have a static method for each operation.
for the math on e.g.
static int plus(int a, int b){
return a+b;
}
Since I want to make the methods binary. If I have (2+3+4) it will need to know it is the same as (2+(3+4)) and make plus(2,plus(3,4));

If anyone can give me any help. Explain somethings. More so show me some java methods I haven't found. It is greatly appreciated.
It was only yesterday I found string.toCharArray(); with saved a for loop.
• January 17th, 2011, 11:09 PM
helloworld922
Re: Parenthetical input
So you want to make a lexer/parser? That's a rather difficult (and interesting) topic. While it's possible to write a parser by hand, it is definitely not recommended for anything but the most basic of parsers. Instead I would recommend using a tool called ANTLR. It lets you generate a lexer and parser using a specified grammar.

There's a very helpful video tutorial series on how to use ANTLR here.