SIGN IN YOUR ACCOUNT TO HAVE ACCESS TO DIFFERENT FEATURES

FORGOT YOUR PASSWORD?

FORGOT YOUR DETAILS?

AAH, WAIT, I REMEMBER NOW!
Openbaraza

Openbaraza

Openbaraza

Baraza is a Swahili word that means a deliberation meeting held by a collective group of people with wisdom.

T : +254 (20) 2243097 / 2227100
Email: info@openbaraza.org

OPENBARAZA
Dew CIS Solutions LTD Barclays Plaza, 12th Floor. Loita Street.

Open in Google Maps
  • Framework
  • Projects
    • Human Resource
      • Human Resource
      • Time Attendance
      • Project Planning
    • Finance Management
      • Business
      • Payroll
    • Investment Management
      • Banking
      • Chama
      • Sacco
    • Case Management
      • Judiciary
    • Real Estate Management
      • Property
    • Academic Management
      • UMIS
      • Schools
  • Forums
    • HCM HR Payroll
    • Business
    • Sacco
    • Banking
  • Blog & News
    • OpenBaraza Framework
    • Databases
    • Java Programming
    • Scrum
  • Contact Us
  • Home
  • Blog & News
  • Java Programming
  • 08. BODMAS IN JAVA
July 4, 2025

08. BODMAS IN JAVA

08. BODMAS IN JAVA

by dennis@dennis.me.ke / Thursday, 03 October 2019 / Published in Java Programming

We shall continue from where we left off last time on Java Programming. Have you heard of mathematical expressions before? Well, if you haven’t we will have a clear understanding of what they are and how to solve them, not just by using a calculator but also using a Java application.

An operation on two numbers is easy, but how do we solve an expression with brackets and multiple operations? It is not as simple as an expression involving two numbers.

Let’s consider the BODMAS rule and learn about simplification of brackets.

Brackets

Of

Division

Multiplication

Addition

Subtraction

This means that we evaluate our expression starting with brackets first then other operations will follow according to the order of precedence. In this java program we shall compute an expression following the BODMAS rule. Consider an expression such as

7+12/ (2*3)-4

How does a computer program evaluate the following expression? Does it start off from right to left? Or does it start from left to right?

The evaluation of this expression is as follows:

7+12/ (6)-4

7+2-4

9-4

5

LIVE A LITTLE…

————————————————————————————————-

A Rasta man went to the bank with a sack full of weed…

Teller : How may I help you sir?

The guy puts the sack of weed on the counter

Rasta Man : I want to open a joint account.

————————————————————————————————-

Following the evaluation of the above expression, we shall begin. First, we created a class that does validation to check if the expression is correctly written removing all the spaces in the expression and irrelevant data. In this class we created the following methods;

  • //Checks if the character at the beginning of the expression is valid

public static boolean validateFirstindex(){

  • //Checks if the end of the expression is valid

public static boolean endExpression () {

  • //Check whether all brackets are balanced

public static boolean checkBrackets() {

  • //ensures the Expression contains valid characters

public static boolean validCharacters () {

  • ensures that two subsequent operators are valid and in the correct order

public static boolean operatorSeq() {

  • //Remove spaces from the expression

public static void removeSpaces () {

  • //when number is followed by an opening bracket, call this method to insert the multiplication operator

public static void insertMultiplication (int index) {

  • //Validates the expression

public static char [] validate (char [] expression) {

Next step, we created a class that does the evaluation of the expression. We used two stacks, one to store operators and the other to store the values. We created different methods which handle specific tasks. Some of the methods used are explained below.

The code below is a snippet of one of the methods that we used to evaluate. You can find the code for the entire program in our GitHub account.

Explanation:

//Stack for numbers: ‘values’

Stack<Double> values = new Stack<Double> ();

// Stack for Operators: ‘ops’

Stack<Character> ops = new Stack<Character> ();

//Declare and Initialize i to 0

int i = 0;

//Loop through the tokens

while ( i < tokens.length ) {

// Current token is a number, push it to stack for numbers

if ((tokens[i] >= ‘0‘ && tokens[i] <= ‘9‘) || tokens[i] == ‘.‘) {

StringBuffer sbuf = new StringBuffer();

// There may be more than one digits in number

int j = i;

while (j < tokens.length) {

if ((tokens[j] >= ‘0‘ && tokens[j] <= ‘9‘) || tokens[j] == ‘.‘){

sbuf.append(tokens[j++]);

}//End of if statement

else break;

}//End of while loop

i = j–1;

values.push(Double.parseDouble(sbuf.toString()));

i++;

}//End of if statement

The other method that we will explain about is the one used to check the operator’s order of precedence.

Explanation:

// Returns true if ‘op2’ has higher or same precedence as ‘op1’, otherwise returns false.

public static boolean hasPrecedence(char op1, char op2) {

if (op2 == ‘(‘ || op2 == ‘)‘){

return false;

}//End of if statement

if ((op1 == ‘&‘ || op1 == ‘*‘ || op1 == ‘/‘) && (op2 == ‘+‘ || op2 == ‘–‘)){

return false;

}//End of if statement

else {

return true;

}//End of else

}//End of method

The last method we will explain is the one used to solve the expression having met all the conditions of a proper expression.

Explanation:

// A utility method to apply an operator ‘op’ on operands ‘a’ and ‘b’. Return the result.

public static double solve(char op, double b, double a) {

switch (op)

{

case ‘+‘:

return a + b;

case ‘–‘:

return a – b;

case ‘*‘:

return a * b;

case ‘&‘:

return a * b;

case ‘/‘:

if (b == 0)

throw new

UnsupportedOperationException(“Cannot divide by zero“);

return a / b;

}//End of switch case

return 0;

}//End of solve method

p { margin-bottom: 0.25cm; direction: ltr; line-height: 115%; text-align: left; }a:link { color: rgb(5, 99, 193); }

0
  • Tweet

About dennis@dennis.me.ke

What you can read next

06. Classes: Store Student Details Using Json Format
04. Control Structures
02. Learning Java in Linux

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • 07. JAVA ARRAYS: Store Student Details Using Arrays and List

  • 06. Classes: Store Student Details Using Json Format

  • 02. SPRINT RETROSPECTIVE

  • 01. SCRUM (DEMO)

  • 05. Variables

Categories

  • Databases
  • Java Programming
  • OpenBaraza Framework
  • Scrum

QUICK LINKS

  • Home
  • Our Stories
  • Contact Us
  • Terms and Conditions
  • Our Policy

VISIT US

Open Baraza
Barclays Plaza, 12th Floor.
Loita Street, Nairobi.

Open in Google Maps

GET IN TOUCH

Tel: +254 (20) 2243097 / 2227100
     +254(726)209214, +254(738)819505
Email: info@openbaraza.org

Follow Us

Could not authenticate you.
  • GET SOCIAL
Openbaraza

© All rights reserved | Open Baraza developed by DewCis Solutions.

TOP