Calculate a simple expression (with.Java)
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.