Signup/Sign In
APRIL 11, 2023

How to Solve the Mathematical expression String in Android App

Technology #android#java

    We have seen different types of app ( calculator apps ) in which the mathematical equation is easily solved. This feature is a very important feature of most modern apps, almost all calculators use this feature such as Google Calculator, Xiaomi calculators, and all other calculators. previously all the apps only solve equations with 2 numbers and one operator ( 2+3, 5*7, 17-2, 8/2 ). But nowadays all the apps can solve long simple mathematical expressions easily without any problem .so let's take the example

    Input : 2+25-10

    Output: 17

    one more example with brackets

    Input : (2+3)*5

    Output: 25

    So to solve this type of long mathematical expression you can follow this article

    Step 1: Create a new Project

    1. Open Your Android Studio Click on "Start a new Android Studio project"(Learn how to set up Android Studio and create your first Android project)

    2. Choose "Empty Activity" from the project template window and click Next

    3. Enter the App Name, Package name, save location, language(Java/Kotlin, we use Java for this tutorial ), and minimum SDK(we are using API 19: Android 4.4 (KitKat))

    4. Next click on the Finish button after filling in the above details

    5. Now, wait for the project to finish building.

    Step 2: Modify activity_main.xml

    Now go to app -> res -> layout -> activity_main.xml and we add EditText , TextView, Buttons as shown below:

    <?xml version = "1.0" encoding = "utf-8"?>
    <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
        xmlns:app = "http://schemas.android.com/apk/res-auto"
        xmlns:tools = "http://schemas.android.com/tools"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        tools:context = ".MainActivity">
    
       <EditText
           android:hint = "Enter the Expression"
           android:textColor = "#FF5722"
           android:id = "@+id/equationEditText"
           android:layout_margin = "16dp"
           android:layout_width = "match_parent"
           android:layout_height = "wrap_content"/>
    
        <TextView
            android:shadowColor = "#2d2d2d"
            android:shadowDx = "2"
            android:shadowDy = "2"
            android:shadowRadius = "2"
            android:layout_margin = "16dp"
            android:textColor = "#0DE162"
            android:textSize = "32dp"
            android:foregroundGravity = "center"
            android:gravity = "center_horizontal"
            android:id = "@+id/textViewResult"
            android:layout_centerInParent = "true"
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content"/>
    
        <Button
            android:background = "#077DDA"
            android:onClick = "sol"
            android:text = "Solve   :)"
            android:layout_margin = "16dp"
            android:layout_below = "@id/equationEditText"
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content"/>
    
    </RelativeLayout>

    In the above XML file, we use EditText to get the mathematical expression from the user, TextView to show the calculated result to the user and show an error when the expression is invalid, Button to perform the calculation on the EditText value, we use the onClick property of Button to call the sol method, which we create later

    Step 3: MainActivity.java file

    Now open the MainActivity.java file and import some basic classes as shown below:

    import androidx.appcompat.app.AppCompatActivity;
    
    import android.graphics.Color;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.util.Stack;
    

    Next, we create the objects of EditText inside MainActivity class as shown below

    public EditText editText;

    Now inside the onCreate method, we initialize the EditText

     editText= ( EditText ) findViewById( R.id.equationEditText );
    

    Next, we create different methods or functions for doing our task as shown below

    1. We will add the public float applyOp( char operatorX, float a, float b) as shown below
      
              public  float applyOp( char operatorX,  float a,  float b)
              {
                  switch ( operatorX)
                  {
                      case '+':
                          return b+a;
                      case '-':
                          return b-a;
                      case '*':
                          return b*a;
                      case '/':
                          if ( a != 0)
                              return b/a;
                  }
                  return 0;
              }
      The above function takes 3 values operatorX , a,b and return the float value according to the operatorX value ( +,-,*,/)
    2. Next e create a function public boolean checkP( char operatorA, char operatorB) as shown below
        public  boolean checkP( char operatorA,  char operatorB)
              {
                  if ( operatorB == '(' || operatorB == ')') {
                      return false;
                  }
                  if (  ( operatorA == '+' || operatorA == '-') && ( operatorB == '*' || operatorB == '/') ) {
                      return false;
                  }
                  else {
                      return true;
                  }
              }

      The above method takes 2 character operatorA and operatorB and using the values it checks the precedence and returns the boolean which is either true or false

    3. Now we write the best part of the program, which is the brain of our program public float letsCalculate( String mS) as shown below

         public  float letsCalculate( String mS)
              {
                  char[] myChar = mS.toCharArray( );
      
                  Stack<Float> myNumStack = new
                          Stack<Float>( );
      
                  Stack<Character> operatorStack = new
                          Stack<Character>( );
      
      
                  for ( int i = 0; i < myChar.length; i++)
                  {
      
                      if ( myChar[i] >= '0' &&
                              myChar[i] <= '9')
                      {
                          StringBuffer stringBuffer = new
                                  StringBuffer( );
      
                         
                          while ( i < myChar.length && myChar[i] >= '0' && myChar[i] <= '9') {
                              stringBuffer.append( myChar[i++]);
                          }
                          myNumStack.push( Float.parseFloat( stringBuffer.toString( )));
      
                        
                          i--;
                      }
      
      
                      else if ( myChar[i] == '(')
                          operatorStack.push( myChar[i]);
      
      
                      else if ( myChar[i] == ')')
                      {
                          while ( operatorStack.peek( ) != '(') {
                              myNumStack.push( applyOp( operatorStack.pop( ),  myNumStack.pop( ),  myNumStack.pop( )));
                          }
                          operatorStack.pop( );
                      }
      
      
                      else if ( myChar[i] == '/' || myChar[i] == '*' || myChar[i] == '+' || myChar[i] == '-')
                      {
      
                          while ( !operatorStack.empty( ) && checkP( myChar[i],  operatorStack.peek( ))) {
                              myNumStack.push( applyOp( operatorStack.pop( ), 
                                      myNumStack.pop( ), 
                                      myNumStack.pop( )));
                          }
      
      
                          operatorStack.push( myChar[i]);
                      }
                  }
      
      
                  while ( !operatorStack.empty( )) {
                      myNumStack.push( applyOp( operatorStack.pop( ),  myNumStack.pop( ),  myNumStack.pop( )));
                  }
      
      
                  return myNumStack.pop( );
              }

      In the above function, we take the string expression and solve it using the stack and return the float value ( which we display in the TextView later ).In the function, we created 2 stack Stack<Float> to store the numeric values and Stack<Character> to store the operators and braces

    The complete code of the MainActivity.java is shown below

    package com.studytonight.project;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.graphics.Color;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.util.Stack;
    
    public class MainActivity extends AppCompatActivity {
    
        EditText editText;
      
        @Override
        protected void onCreate( Bundle savedInstanceState) {
            super.onCreate( savedInstanceState);
            setContentView( R.layout.activity_main);
            editText= (  EditText ) findViewById(  R.id.equationEditText );
    
        }
    
      
        
    
    
    
            public  float applyOp( char operatorX,  float a,  float b)
            {
                switch ( operatorX)
                {
                    case '+':
                        return b+a;
                    case '-':
                        return b-a;
                    case '*':
                        return b*a;
                    case '/':
                        if ( a != 0)
                            return b/a;
                }
                return 0;
            }
    
    
            public  boolean checkP( char operatorA,  char operatorB)
            {
                if ( operatorB == '(' || operatorB == ')') {
                    return false;
                }
                if (  ( operatorA == '+' || operatorA == '-') && ( operatorB == '*' || operatorB == '/') ) {
                    return false;
                }
                else {
                    return true;
                }
            }
            public  float letsCalculate( String mS)
            {
                char[] myChar = mS.toCharArray( );
    
    
                Stack<Float> myNumStack = new
                        Stack<Float>( );
    
    
                Stack<Character> operatorStack = new
                        Stack<Character>( );
    
                for ( int i = 0; i < myChar.length; i++)
                {
    
                    if ( myChar[i] >= '0' &&
                            myChar[i] <= '9')
                    {
                        StringBuffer stringBuffer = new
                                StringBuffer( );
    
                       
                        while ( i < myChar.length && myChar[i] >= '0' && myChar[i] <= '9') {
                            stringBuffer.append( myChar[i++]);
                        }
                        myNumStack.push( Float.parseFloat( stringBuffer.toString( )));
    
                      
                        i--;
                    }
    
    
                    else if ( myChar[i] == '(')
                        operatorStack.push( myChar[i]);
    
    
                    else if ( myChar[i] == ')')
                    {
                        while ( operatorStack.peek( ) != '(') {
                            myNumStack.push( applyOp( operatorStack.pop( ),  myNumStack.pop( ),  myNumStack.pop( )));
                        }
                        operatorStack.pop( );
                    }
    
    
                    else if ( myChar[i] == '/' || myChar[i] == '*' || myChar[i] == '+' || myChar[i] == '-')
                    {
    
                        while ( !operatorStack.empty( ) && checkP( myChar[i],  operatorStack.peek( ))) {
                            myNumStack.push( applyOp( operatorStack.pop( ), 
                                    myNumStack.pop( ), 
                                    myNumStack.pop( )));
                        }
    
    
                        operatorStack.push( myChar[i]);
                    }
                }
    
    
                while ( !operatorStack.empty( )) {
                    myNumStack.push( applyOp( operatorStack.pop( ),  myNumStack.pop( ),  myNumStack.pop( )));
                }
    
    
                return myNumStack.pop( );
            }
    
    
            public  void sol( View x)
            {
    
                try {
                    ( ( TextView)findViewById( R.id.textViewResult)).setTextColor( Color.GREEN);
    
                    ( ( TextView) findViewById( R.id.textViewResult)).setText( "Answer \n" + letsCalculate( editText.getText( ).toString( )));
                }
                catch ( Exception e)
                {
                    ( ( TextView)findViewById( R.id.textViewResult)).setTextColor( Color.RED);
                    ( ( TextView)findViewById( R.id.textViewResult)).setText( "Error");
    
                }
    
            }
    
    }

    Output:

    In the below snapshots, you can see how our program will look in the android application.

    When we first open the app: It allows the user to enter the expression

    Making an android app

    When the user enters the mathematical expression

    Making an android app

    When the user clicks on Button: It solves the expression

    Making an android app

    We can also use the brackets in the expression

    Making an android app

    Conclusion:

    In just 3 simple steps we have shown you the basic example for solving mathematical expression in your android app. If you face any issue while doing this, please share it in the comment section below and we will be happy to help.

    K S Lohan is an accomplished author and expert in technical writing on Android language and develop android App. He is highly skilled at communicating complex programming concepts in a clear and concise manner.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS