-3

Currently learning Java, and trying to parse a maths equation for valid inputs:

For example, the user has to input integers in the form:

Operand Operator Operand

in that specific order, and the program would then need to be able to tell if the inputs were in that form, and then work out the simple equation.

An example would be:

4 * 8 which the result would give as 32

the program would also reject something like 45.6 * 0.3, or 45 + 3 / 4

For this to work, do I have to use regular expression, or some other method of if loops?

5
  • 1
    there're zillions of math parser implementations, just google for "java math parser". And not, most of them don't use regexps, there's no need. Sep 30, 2017 at 22:03
  • You may use regex if your requirement is just checking for valid user input.
    – SomeDude
    Sep 30, 2017 at 22:07
  • You should research a bit, try something out and post a question if you get stuck. As is, you question is too broad.
    – Dici
    Sep 30, 2017 at 22:07
  • 1
    Your first step should be to define precisely, for yourself, exactly what "Operand" is acceptable. Just saying "integer" is not enough. Do you accept 10.0? What about 1e+02? Also consider 010 and +10 and -10. Sep 30, 2017 at 23:32
  • Regex is the wrong approach. The problem with most requests like this is that the "math" they restrict themselves so is little more than simple arithmetic with +, -, *, and / operands. It's not very sophisticated or useful.
    – duffymo
    Oct 1, 2017 at 1:39

2 Answers 2

2

You can use RegEx to on one hand, get rid of the invalid input, and on the other hand make use of the groups to extract the operands and operation and apply the math

/^(\\d+)\\s*([+\\-*\\/])\\s*(\\d+)$/

Edit:

As Rory Daulton pointed out, the signed integers are excluded from the above RegEx, so the below one should be used instead

/^([+\\-]?\\d+)\\s*([+\\-*\\/])\\s*([+\\-]?\\d+)$/
4
  • How can I implement that into the code? Like, where would that go?
    – Nawlidge
    Sep 30, 2017 at 22:07
  • I left the easiest part for you Sep 30, 2017 at 22:09
  • I keep getting an incorrect escape character error, could you give me a sample line, as to where it would belong?
    – Nawlidge
    Sep 30, 2017 at 22:33
  • @RoryDaulton you are right, it was not intended, I'm going to update the suggestion and add both signs Sep 30, 2017 at 23:50
0

Take look that: https://stackoverflow.com/a/11009403/8701820

^([-+/*]\d+(\.\d+)?)*

Also you can check this website: https://regex101.com

1
  • That's wrong, he wants integer inputs, and only two operands and one operation, as far as I can see Sep 30, 2017 at 22:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.