-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?

Nawlidge
  • 105
  • 1
  • 2
  • 9
  • 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. – user3159253 Sep 30 '17 at 22:03
  • You may use [regex](https://regex101.com/r/KLovyh/1) if your requirement is just checking for valid user input. – SomeDude Sep 30 '17 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 '17 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`. – Rory Daulton Sep 30 '17 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 01 '17 at 01:39

2 Answers2

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+)$/
Mohamed Shaaban
  • 1,129
  • 6
  • 13
0

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

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

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