0

I want to take the string(s): “6 + 3”; “6 – 3”, “6 / 3” and “6 * 3” and be able to do the required arithmetic operation. I know that I have to use a regular expression to do this. So far, I have:

    int num1 = 0, num2 = 0, count = 0;

    Scanner input = new Scanner(System.in);
    Pattern stringPattern = Pattern.compile("\\d+|[+-/*]");     
    System.out.println("Please enter an arithmetic operation: ");
    String arith = input.nextLine();
    Matcher stringMatch = stringPattern.matcher(arith);
        while(stringMatch.find()){
            System.out.println(stringMatch.group());
        if(Integer.parseInt(stringMatch.group()) >=Integer.MIN_VALUE){
            if(count == 0){
                num1 = Integer.parseInt(stringMatch.group());
            }
            else{
                    num2 = Integer.parseInt(stringMatch.group());
            }
        count++;
        }
}

The problem I have is getting the arithmetic sign out of the string and using it as an unary operator.

Bob
  • 27
  • 5
  • 2
    Dash has to come at the end, otherwise it's interpreted as a group (remember `[A-Z]`? `[+-/]` is the same thing). – Sergey Kalinichenko Jul 23 '16 at 23:52
  • There are no unary operators in your example. However you should certainly *not* use regular expressions for this. You need an arithmetic expression parser. – user207421 Jul 24 '16 at 00:43
  • dashblinkenlight: this is not an answer to my question. Yes, I have changed the code as you suggested; however, I still am unable to parse the arithmetic operators out of it. – Bob Jul 24 '16 at 00:48
  • 1
    Have a look at the reply of [boann](http://stackoverflow.com/users/964243/boann) in response to the question [Evaluating a math expression given in string form](http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) – Imran Ali Jul 24 '16 at 01:00

0 Answers0