-3

I'm a beginner--I'm supposed to write a class that calculates the result of a given math expression in a char array, taking into account precedence with the operators +, -, *, and /. For example:

Input: char[] a = {'1', '1',’1’, '-', '1', '2',‘*’, ‘2’}, Output: 87

All the solutions I can think of involve snarls of if statements or messy nested loops. Any advice? Thanks in advance for any help. Here's what I have so far, by the way:

import java.util.Scanner;

public class MathInCharArray {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        System.out.print("Input a calculation without spaces, using the operators +, -, *, or /: ");
        String userInput = scnr.next();
        char[] equationArray = new char[userInput.length()];
        boolean operator = false;

        for (int i = 0; i < userInput.length() - 1; ++i) {
            equationArray[i] = userInput.charAt(i);
        }

        for (int i = 1; i < userInput.length() - 1; ++i) {
            for (int j = 0; j < userInput.length() - 2; ++j) {
                
            }
        }

    }
}
  • Have you considered using Javas `enum`? Whilst it might be considered a slightly more advanced topic, `enum` is quite a good fit here especially if you can make use of constant specific methods. – Gavin Oct 15 '20 at 07:19
  • 1
    Use a stack. Push/Pop arguments. This is a classical problem that has been solved upmteenth times. – Polygnome Oct 15 '20 at 07:20
  • Usually with an operand stack (with values like "11") and an operator stack with values (like "+"). You start with an empty operand "", also after every binary operator. – Joop Eggen Oct 15 '20 at 07:23
  • Well, one of the constructors of `String` accepts a `char[]`... – MC Emperor Oct 15 '20 at 07:44
  • @jhamon Yes, it does! Thanks so much! – Spam McSpam Oct 15 '20 at 07:59

1 Answers1

0

You could try concatenating both numbers into a string variables, storing the operator into a separate variable, and then use a switch statement with your operator. From there you can cast your numbers into doubles as you calculate the expression.