'Find to find different arithmetic operations
I am currently learning the basics of test automation.
My tutor handed me the following exercise:
Create a calculator that reads user input & that can perform these math operations: +-*/%
The calculator should be able to distinguish between 1) Binary operators (e.g. 20+20) & 2) Unary operators (e.g. -43)
It should be possible to quit the program by typing
:qI should use regular expressions to recognize the following parts of the user input
- Operators & 2. Operands
This is my first draft to first handle standard operations with two operands.
Can someone explain me how to find the correct regular expression and split the input into correct variables which then can be used for the correct calculations?
public class regextest {
public static void main(String[] args) {
char operator;
Double number1, number2, result;
// ask users to enter operator
System.out.println("Type in your operation:");
String input = new Scanner(System.in).nextLine();
// Regular expression to split the string
Pattern pattern = Pattern.compile //need help to find the correct regex and to split and save it to correct variables
Matcher matcher = pattern.matcher(input);
switch (operator) {
// performs addition between numbers
case '+':
result = number1 + number2;
System.out.println(result);
break;
// performs subtraction between numbers
case '-':
result = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;
// performs multiplication between numbers
case '*':
result = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;
// performs division between numbers
case '/':
result = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + result);
break;
// performs modulo between numbers
case '%':
result = number1 % number2;
System.out.println(number1 + " % " + number2 + " = " + result);
break;
default:
System.out.println("Invalid operation!");
break;
}
}
}
Solution 1:[1]
This makes some assumptions, but works with the examples provided. First capture group is the first number, second capture group is the operator, third is the second number. Allows for optional spaces and an equals sign at the end. If other unary operators are required (++, --, etc.), you could use a second regex for those.
^\s*?(-?\d+)\s*?([+\-\*\/%])\s*?(-?\d+)\s*?=?\s*$
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ejkeep |
