Contents

Calculate a simple expression (with.Java)

   Oct 16, 2023     2 min read

In this article, we learned about calculating simple expressions.

We’ll do this by solving a coding test problem, reflecting on the problem we solved, and learning about other ways to solve it.

Let’s start with the problem

Problem

The string binomial is given as a parameter.

binomial is a binomial of the form β€œa op b”, where a and b are non-negative integers, and op is one of β€˜+’, β€˜-β€˜, or β€˜*’.

Write a solution function that returns an integer that computes the given expression.

Example input and output

binomial: β€œ43 + 12”

result: 55

My solution to the problem

class Solution {
    public int solution(String binomial) {
        String[] parts = binomial.split(" ");

        int a = Integer.parseInt(parts[0]);
        int b = Integer.parseInt(parts[2]);

        String op = parts[1];

        int result = 0;
        switch (op) {
            case "+":
                result = a + b;
                break;
            case "-":
                result = a - b;
                break;
            case "*":
                result = a * b;
                break;
        }

        return result;
    }
}
Solution

String[] parts = binomial.split(β€œ β€œ);: Splits the given binomial string based on whitespace and stores it in the parts array. This allows us to separate the operands and operators that are components of the binomial.

int a = Integer.parseInt(parts[0]); and int b = Integer.parseInt(parts[2]);: convert the first and third elements of the parts array to integers and store them in the operands a and b. This extracts the numeric part of the binomial.

String op = parts[1];: Stores the second element of the parts array in the operator string op. This operator will be one of β€œ+”, β€œ-β€œ, or β€œ*”.

int result = 0;: Initialize the variable result to store the result value.

switch (op) { … }: Performs an operation using the switch statement based on the value of op.

case β€œ+”: : Performs an addition operation and stores the result in result.

case β€œ-β€œ: : Performs a subtraction operation and stores the result in result.

case β€œ*”: : Performs a multiplication operation and stores the result in result.

return result;: Returns the calculated result.