How to Make a Scientific Calculator Android App using Kotlin?
Last Updated :
23 Jul, 2025
The calculator is the app that is present on every android device. This app comes pre-installed or we can also install another application from Play Store. It is one of the most used applications for college students for making any calculations. In this article, we will take a look at building a simple scientific calculator app in Android using Kotlin.

Note: To build a simple calculator app please refer to this article How to build a simple Calculator app using Android Studio?
What we are going to build in this article?
We will be building a scientific calculator in which we will be performing several mathematical operations such as addition, subtraction, square root, factorial, and many more. A sample video is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Note that select Kotlin as the programming language.
Step 2: Adding new colors to the colors.xml file
Navigate to the app > res > values > colors.xml file and add the below code to it for different colors. Comments are added in the code to get to know in more detail.
colors.xml:
XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#0F9D58</color>
<color name="purple_500">#0F9D58</color>
<color name="purple_700">#0F9D58</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<!--three different shades of black color-->
<color name="blac_shade_1">#292D36</color>
<color name="black_shade_2">#272B33</color>
<color name="black_shade_3">#22252D</color>
<color name="yellow">#ffa500</color>
</resources>
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
activity_main.xml:
XML
<?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"
android:background="@color/black_shade_3"
tools:context=".MainActivity">
<TextView
android:id="@+id/idTVSecondary"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="@color/black_shade_3"
android:gravity="bottom"
android:maxLines="1"
android:padding="10dp"
android:paddingTop="30dp"
android:text=""
android:textAlignment="viewEnd"
android:textColor="@color/white"
android:textSize="15sp"
tools:ignore="RtlCompat" />
<TextView
android:id="@+id/idTVprimary"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_below="@id/idTVSecondary"
android:background="@color/black_shade_3"
android:gravity="bottom"
android:maxLines="1"
android:padding="10dp"
android:text=""
android:textAlignment="viewEnd"
android:textColor="#fff"
android:textSize="50sp"
tools:ignore="RtlCompat" />
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/idTVprimary"
android:background="@color/blac_shade_1"
app:cardCornerRadius="4dp"
app:cardElevation="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="7"
android:background="@color/blac_shade_1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="7">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/bac"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="AC"
android:textColor="@color/yellow"
android:textSize="15sp"
tools:targetApi="lollipop" />
<Button
android:id="@+id/bc"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="C"
android:textColor="@color/yellow"
android:textSize="15sp" />
<Button
android:id="@+id/bbrac1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="("
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bbrac2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text=")"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="5">
<Button
android:id="@+id/bsin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="sin"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bcos"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="cos"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/btan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="tan"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/blog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="log"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bln"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="ln"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="5">
<Button
android:id="@+id/bfact"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="x!"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bsquare"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="x²"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bsqrt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="√"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/binv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="1/x"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bdiv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="÷"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/b7"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="7"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b8"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="8"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b9"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="9"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bmul"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="×"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/b4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="4"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b5"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="5"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b6"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="6"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bminus"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="-"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/b1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="1"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="2"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="3"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bplus"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="+"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/bpi"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="π"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b0"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="0"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bdot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="."
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bequal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="="
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
MainActivity.kt:
Kotlin
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
// creating variables for our text view and button
lateinit var tvsec: TextView
lateinit var tvMain: TextView
lateinit var bac: Button
lateinit var bc: Button
lateinit var bbrac1: Button
lateinit var bbrac2: Button
lateinit var bsin: Button
lateinit var bcos: Button
lateinit var btan: Button
lateinit var blog: Button
lateinit var bln: Button
lateinit var bfact: Button
lateinit var bsquare: Button
lateinit var bsqrt: Button
lateinit var binv: Button
lateinit var b0: Button
lateinit var b9: Button
lateinit var b8: Button
lateinit var b7: Button
lateinit var b6: Button
lateinit var b5: Button
lateinit var b4: Button
lateinit var b3: Button
lateinit var b2: Button
lateinit var b1: Button
lateinit var bpi: Button
lateinit var bmul: Button
lateinit var bminus: Button
lateinit var bplus: Button
lateinit var bequal: Button
lateinit var bdot: Button
lateinit var bdiv: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// initializing all our variables.
tvsec = findViewById(R.id.idTVSecondary)
tvMain = findViewById(R.id.idTVprimary)
bac = findViewById(R.id.bac)
bc = findViewById(R.id.bc)
bbrac1 = findViewById(R.id.bbrac1)
bbrac2 = findViewById(R.id.bbrac2)
bsin = findViewById(R.id.bsin)
bcos = findViewById(R.id.bcos)
btan = findViewById(R.id.btan)
blog = findViewById(R.id.blog)
bln = findViewById(R.id.bln)
bfact = findViewById(R.id.bfact)
bsquare = findViewById(R.id.bsquare)
bsqrt = findViewById(R.id.bsqrt)
binv = findViewById(R.id.binv)
b0 = findViewById(R.id.b0)
b9 = findViewById(R.id.b9)
b8 = findViewById(R.id.b8)
b7 = findViewById(R.id.b7)
b6 = findViewById(R.id.b6)
b5 = findViewById(R.id.b5)
b4 = findViewById(R.id.b4)
b3 = findViewById(R.id.b3)
b2 = findViewById(R.id.b2)
b1 = findViewById(R.id.b1)
bpi = findViewById(R.id.bpi)
bmul = findViewById(R.id.bmul)
bminus = findViewById(R.id.bminus)
bplus = findViewById(R.id.bplus)
bequal = findViewById(R.id.bequal)
bdot = findViewById(R.id.bdot)
bdiv = findViewById(R.id.bdiv)
// adding on click listener to our all buttons.
b1.setOnClickListener {
// on below line we are appending
// the expression to our text view.
tvMain.text = (tvMain.text.toString() + "1")
}
b2.setOnClickListener {
// on below line we are appending
// the expression to our text view.
tvMain.text = (tvMain.text.toString() + "2")
}
b3.setOnClickListener {
// on below line we are appending
// the expression to our text view.
tvMain.text = (tvMain.text.toString() + "3")
}
b4.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "4")
}
b5.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "5")
}
b6.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "6")
}
b7.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "7")
}
b8.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "8")
}
b9.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "9")
}
b0.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "0")
}
bdot.setOnClickListener {
tvMain.text = (tvMain.text.toString() + ".")
}
bplus.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "+")
}
bdiv.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "/")
}
bbrac1.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "(")
}
bbrac2.setOnClickListener {
tvMain.text = (tvMain.text.toString() + ")")
}
bpi.setOnClickListener {
// on clicking on pi button we are adding
// pi value as 3.142 to our current value.
tvMain.text = (tvMain.text.toString() + "3.142")
tvsec.text = (bpi.text.toString())
}
bsin.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "sin")
}
bcos.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "cos")
}
btan.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "tan")
}
binv.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "^" + "(-1)")
}
bln.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "ln")
}
blog.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "log")
}
bminus.setOnClickListener {
// on clicking on minus we are checking if
// the user has already a minus operation on screen.
// if minus operation is already present
// then we will not do anything.
val str: String = tvMain.text.toString()
if (!str.get(index = str.length - 1).equals("-")) {
tvMain.text = (tvMain.text.toString() + "-")
}
}
bmul.setOnClickListener {
// if mul sign is not present in our
// text view then only we are adding
// the multiplication operator to it.
val str: String = tvMain.text.toString()
if (!str.get(index = str.length - 1).equals("*")) {
tvMain.text = (tvMain.text.toString() + "*")
}
}
bsqrt.setOnClickListener {
if (tvMain.text.toString().isEmpty()) {
// if the entered number is empty we are displaying an error message.
Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show()
} else {
val str: String = tvMain.text.toString()
// on below line we are calculation
// square root of the given number.
val r = Math.sqrt(str.toDouble())
// on below line we are converting our double
// to string and then setting it to text view.
val result = r.toString()
tvMain.setText(result)
}
}
bequal.setOnClickListener {
val str: String = tvMain.text.toString()
// on below line we are calling an evaluate
// method to calculate the value of expressions.
val result: Double = evaluate(str)
// on below line we are getting result
// and setting it to text view.
val r = result.toString()
tvMain.setText(r)
tvsec.text = str
}
bac.setOnClickListener {
// on clicking on ac button we are clearing
// our primary and secondary text view.
tvMain.setText("")
tvsec.setText("")
}
bc.setOnClickListener {
// on clicking on c button we are clearing
// the last character by checking the length.
var str: String = tvMain.text.toString()
if (!str.equals("")) {
str = str.substring(0, str.length - 1)
tvMain.text = str
}
}
bsquare.setOnClickListener {
if (tvMain.text.toString().isEmpty()) {
// if the entered number is empty we are displaying an error message.
Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show()
} else {
// on below line we are getting the expression and then calculating the square of the number
val d: Double = tvMain.getText().toString().toDouble()
// on below line we are calculating the square.
val square = d * d
// after calculating the square we
// are setting it to text view.
tvMain.setText(square.toString())
// on below line we are setting
// the d to secondary text view.
tvsec.text = "$d²"
}
}
bfact.setOnClickListener {
if (tvMain.text.toString().isEmpty()) {
// if the entered number is empty we are displaying an error message.
Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show()
} else {
// on below line we are getting int value
// and calculating the factorial value of the entered number.
val value: Int = tvMain.text.toString().toInt()
val fact: Int = factorial(value)
tvMain.setText(fact.toString())
tvsec.text = "$value`!"
}
}
}
fun factorial(n: Int): Int {
// this method is use to find factorial
return if (n == 1 || n == 0) 1 else n * factorial(n - 1)
}
fun evaluate(str: String): Double {
return object : Any() {
// on below line we are creating variable
// for tracking the position and char pos.
var pos = -1
var ch = 0
// below method is for moving to next character.
fun nextChar() {
// on below line we are incrementing our position
// and moving it to next position.
ch = if (++pos < str.length) str[pos].toInt() else -1
}
// this method is use to check the extra space
// present int the expression and removing it.
fun eat(charToEat: Int): Boolean {
while (ch == ' '.toInt()) nextChar()
// on below line we are checking the char pos
// if both is equal then we are returning it to true.
if (ch == charToEat) {
nextChar()
return true
}
return false
}
// below method is to parse our
// expression and to get the ans
// in this we are calling a parse
// expression method to calculate the value.
fun parse(): Double {
nextChar()
val x = parseExpression()
if (pos < str.length) throw RuntimeException("Unexpected: " + ch.toChar())
return x
}
// in this method we will only perform addition and
// subtraction operation on the expression.
fun parseExpression(): Double {
var x = parseTerm()
while (true) {
if (eat('+'.toInt())) x += parseTerm() // addition
else if (eat('-'.toInt())) x -= parseTerm() // subtraction
else return x
}
}
// in below method we will perform
// only multiplication and division operation.
fun parseTerm(): Double {
var x = parseFactor()
while (true) {
if (eat('*'.toInt())) x *= parseFactor() // multiplication
else if (eat('/'.toInt())) x /= parseFactor() // division
else return x
}
}
// below method is use to parse the factor
fun parseFactor(): Double {
//on below line we are checking for addition
// and subtraction and performing unary operations.
if (eat('+'.toInt())) return parseFactor() // unary plus
if (eat('-'.toInt())) return -parseFactor() // unary minus
// creating a double variable for ans.
var x: Double
// on below line we are creating
// a variable for position.
val startPos = pos
// on below line we are checking
// for opening and closing parenthesis.
if (eat('('.toInt())) { // parentheses
x = parseExpression()
eat(')'.toInt())
} else if (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) {
// numbers
while (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) nextChar()
// on below line we are getting sub string from our string using start and pos.
x = str.substring(startPos, pos).toDouble()
} else if (ch >= 'a'.toInt() && ch <= 'z'.toInt()) {
// on below function we are checking for the operator in our expression.
while (ch >= 'a'.toInt() && ch <= 'z'.toInt()) nextChar()
val func = str.substring(startPos, pos)
// calling a method to parse our factor.
x = parseFactor()
// on below line we are checking for square root.
x =
if (func == "sqrt") Math.sqrt(x)
// on below line we are checking for sin function
// and calculating sin function using Math class.
else if (func == "sin") Math.sin(
Math.toRadians(x)
// on below line we are calculating the cos value
) else if (func == "cos") Math.cos(
Math.toRadians(x)
// on below line we are calculating
// the tan value of our expression.
) else if (func == "tan")
Math.tan(Math.toRadians(x))
// on below line we are calculating
// log value of the expression.
else if (func == "log")
Math.log10(x)
// on below line we are calculating
// ln value of expression.
else if (func == "ln") Math.log(x)
// f we get any error then
// we simply return the exception.
else throw RuntimeException(
"Unknown function: $func"
)
} else {
// if the condition not satisfy then we are returning the exception
throw RuntimeException("Unexpected: " + ch.toChar())
}
// on below line we are calculating the power of the expression.
if (eat('^'.toInt())) x = Math.pow(x, parseFactor()) // exponentiation
return x
}
// at last calling a parse for our expression.
}.parse()
}
}
Now run your app to see the output of the app.
Output:
How to Make a Scientific Calculator Android App
Similar Reads
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Overview
Introduction to KotlinKotlin is a statically typed, general-purpose programming language developed by JetBrains, which has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 as a new language for the JVM. Kotlin is an object-oriented language, and a better lang
4 min read
Kotlin Environment setup for Command LineTo set up a Kotlin environment for the command line, you need to do the following steps:Install the Java Development Kit (JDK): Kotlin runs on the Java virtual machine, so you need to have the JDK installed. You can download the latest version from the official Oracle website.Download the Kotlin com
2 min read
Kotlin Environment setup with Intellij IDEAKotlin is a statically typed, general-purpose programming language developed by JetBrains that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011. Kotlin is object-oriented language and a better language than Java, but still be fully i
2 min read
Hello World program in KotlinHello, World! It is the first basic program in any programming language. Let's write the first program in the Kotlin programming language. The "Hello, World!" program in Kotlin: Open your favorite editor, Notepad or Notepad++, and create a file named firstapp.kt with the following code. // Kotlin He
2 min read
Basics
Kotlin Data TypesThe most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects.There are different data types
3 min read
Kotlin VariablesIn Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. The declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type o
2 min read
Kotlin OperatorsOperators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example:Kotlinfun main(args: Array<String>) { var a= 10 + 20 println(a) }Output:30Explanation: Here, â+â is an additio
4 min read
Kotlin Standard Input/OutputIn this article, we will discuss how to take input and how to display the output on the screen in Kotlin. Kotlin standard I/O operations are performed to flow a sequence of bytes or byte streams from an input device, such as a Keyboard, to the main memory of the system and from main memory to an out
4 min read
Kotlin Type ConversionType conversion (also called as Type casting) refers to changing the entity of one data type variable into another data type. As we know Java supports implicit type conversion from smaller to larger data types. An integer value can be assigned to the long data type. Example: Javapublic class Typecas
2 min read
Kotlin Expression, Statement and BlockEvery Kotlin program is made up of parts that either calculate values, called expressions, or carry out actions, known as statements. These parts can be organized into sections called blocks. Table of ContentKotlin ExpressionKotlin StatementKotlin BlockKotlin ExpressionAn expression in Kotlin is mad
4 min read
Control Flow
Kotlin if-else expressionDecision Making in programming is similar to decision-making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. If t
4 min read
Kotlin while loopIn programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines.While loopIt cons
2 min read
Kotlin do-while loopLike Java, the do-while loop is a control flow statement that executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, depending on a Boolean condition at the end of the do-while block. It contrasts with the while loop because the while l
2 min read
Kotlin for loopIn Kotlin, the for loop is equivalent to the foreach loop of other languages like C#. Here for loop is used to traverse through any data structure that provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of the for loop in Kot
4 min read
Kotlin when expressionIn Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to
6 min read
Kotlin Unlabelled breakWhen we are working with loops and want to stop the execution of loop immediately if a certain condition is satisfied, in this case, we can use either break or return expression to exit from the loop. In this article, we will discuss learn how to use break expression to exit a loop. When break expre
4 min read
Kotlin labelled continueIn this article, we will learn how to use continue in Kotlin. While working with a loop in programming, sometimes, it is desirable to skip the current iteration of the loop. In that case, we can use the continue statement in the program. continue is used to repeat the loop for a specific condition.
4 min read
Array & String
Functions
Kotlin functionsIn Kotlin, functions are used to encapsulate a piece of behavior that can be executed multiple times. Functions can accept input parameters, return values, and provide a way to encapsulate complex logic into reusable blocks of code. Table of ContentWhat are Functions?Example of a FunctionTypes of Fu
7 min read
Kotlin Default and Named argumentIn most programming languages, we need to specify all the arguments that a function accepts while calling that function, but in Kotlin, we need not specify all the arguments that a function accepts while calling that function, so it is one of the most important features. We can get rid of this const
7 min read
Kotlin RecursionIn this tutorial, we will learn about Kotlin Recursive functions. Like other programming languages, we can use recursion in Kotlin. A function that calls itself is called a recursive function, and this process of repetition is called recursion. Whenever a function is called then there are two possib
3 min read
Kotlin Tail RecursionIn a traditional recursion call, we perform our recursive call first, and then we take the return value of the recursive call and calculate the result. But in tail recursion, we perform the calculation first, and then we execute the recursive call, passing the results of the current step to the next
2 min read
Kotlin Lambdas Expressions and Anonymous FunctionsIn this article, we are going to learn lambdas expression and anonymous function in Kotlin. While syntactically similar, Kotlin and Java lambdas have very different features. Lambdas expression and Anonymous function both are function literals means these functions are not declared but passed immedi
6 min read
Kotlin Inline FunctionsIn Kotlin, higher-order functions and lambda expressions are treated like objects. This means they can use up memory, which can slow down your program. To help with this, we can use the 'inline' keyword. This keyword tells the compiler not to create separate memory spaces for these functions. Instea
5 min read
Kotlin infix function notationIn this article, we will learn about infix notation used in Kotlin functions. In Kotlin, a function marked with infix keyword can also be called using infix notation means calling without using parenthesis and dot. There are two types of infix function notation in KotlinTable of ContentStandard libr
5 min read
Kotlin Higher-Order FunctionsKotlin language has superb support for functional programming. Kotlin functions can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions. Higher-Order FunctionIn Kotlin, a function that can accept a function as a parameter or return a func
6 min read
Collections
Kotlin CollectionsIn Kotlin, collections are used to store and manipulate groups of objects or data. There are several types of collections available in Kotlin, including:Collection NameDescriptionLists Ordered collections of elements that allow duplicates.Sets Unordered collections of unique elements.Maps Collection
6 min read
Kotlin list : ArraylistThe ArrayList class is used to create a dynamic array in Kotlin. Dynamic array states that we can increase or decrease the size of an array as a prerequisite. It also provides read and write functionalities. ArrayList may contain duplicates and is non-synchronized in nature. We use ArrayList to acce
6 min read
Kotlin list : listOf()In Kotlin, a List is a generic, ordered collection of elements. Lists are very common in everyday programming as they allow us to store multiple values in a single variable. Kotlin provides two types of lists - Immutable Lists (which cannot be changed and created using listOf()) and Mutable Lists (w
7 min read
Kotlin Set : setOf()In Kotlin, a Set is a generic unordered collection of elements that does not allow duplicate elements. Kotlin provides two main types of sets:Immutable Set: Created using setOf() â supports only read-only operations.Mutable Set: Created using mutableSetOf() â supports both read and write operations.
4 min read
Kotlin hashSetOf()In Kotlin, a HashSet is a generic, unordered collection that holds unique elements only. It does not allow duplicates and provides constant-time performance for basic operations like add, remove, and contains, thanks to its internal hashing mechanism. The hashSetOf() function in Kotlin creates a mut
4 min read
Kotlin Map : mapOf()In Kotlin, a Map is a collection that stores data in key-value pairs. Each key in a map is unique, and the map holds only one value for each key. If a key is repeated, only the last value is retained.Kotlin distinguishes between:Immutable maps (mapOf()) - read-onlyMutable maps (mutableMapOf()) - rea
5 min read
Kotlin HashmapIn Kotlin, a HashMap is a collection that stores key-value pairs, where each key must be unique, but values can be duplicated. It is a hash table based implementation of the MutableMap interface. Map keys are unique and the map holds only one value for each key. It is represented as HashMap<key,
7 min read
OOPs Concept
Kotlin Class and ObjectsIn Kotlin, classes and objects are used to represent objects in the real world. A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or fields), and implementations of behavior (member functions or methods). An object is an i
4 min read
Kotlin Nested class and Inner classIn Kotlin, you can define a class inside another class. Such classes are categorized as either nested classes or inner classes, each with different behavior and access rules.Nested ClassA nested class is a class declared inside another class without the inner keyword. By default, a nested class does
3 min read
Kotlin Setters and GettersIn Kotlin, properties are a core feature of the language, providing a clean and concise way to encapsulate fields while maintaining control over how values are accessed or modified. Each property can have getters and setters, which are automatically generated but can be customized as needed.Kotlin P
4 min read
Kotlin Class Properties and Custom AccessorsIn object-oriented programming, encapsulation is one of the most fundamental principles. It refers to bundling data (fields) and the code that operates on that data (methods) into a single unit - the class. Kotlin takes this principle even further with properties, a feature that replaces traditional
3 min read
Kotlin ConstructorA constructor is a special member function that is automatically called when an object of a class is created. Its main purpose is to initialize properties or perform setup operations. In Kotlin, constructors are concise, expressive, and provide significant flexibility with features like default para
6 min read
Kotlin Visibility ModifiersIn Kotlin, visibility modifiers are used to control the visibility of a class, its members (properties, functions, and nested classes), and its constructors. The following are the visibility modifiers available in Kotlin:private: The private modifier restricts the visibility of a member to the conta
6 min read
Kotlin InheritanceKotlin supports inheritance, which allows you to define a new class based on an existing class. The existing class is known as the superclass or base class, and the new class is known as the subclass or derived class. The subclass inherits all the properties and functions of the superclass, and can
10 min read
Kotlin InterfacesIn Kotlin, an interface is a collection of abstract methods and properties that define a common contract for classes that implement the interface. An interface is similar to an abstract class, but it can be implemented by multiple classes, and it cannot have state.Interfaces are custom types provide
7 min read
Kotlin Data ClassesIn Kotlin, we often create classes just to hold data. These are called data classes, and they are marked with the data keyword. Kotlin automatically creates some useful functions for these classes, so you donât have to write them yourself.What Is a Data Class?A data class is a class that holds data.
3 min read
Kotlin Sealed ClassesKotlin introduces a powerful concept that doesn't exist in Java: sealed classes. In Kotlin, sealed classes are used when you know in advance that a value can only have one of a limited set of types. They let you create a restricted class hierarchy, meaning all the possible subclasses are known at co
4 min read
Kotlin Abstract classIn Kotlin, an abstract class is a class that cannot be instantiated and is meant to be subclassed. An abstract class may contain both abstract methods (methods without a body) and concrete methods (methods with a body).An abstract class is used to provide a common interface and implementation for it
5 min read
Enum Classes in KotlinIn programming, sometimes we want a variable to have only a few specific values. For example, days of the week or card suits (like Heart, Spade, etc.). To make this possible, most programming languages support something called enumeration or enum.Enums are a list of named constants. Kotlin supports
4 min read
Kotlin extension functionKotlin provides a powerful feature called Extension Functions that allows us to add new functions to existing classes without modifying them or using inheritance. This makes our code more readable, reusable, and clean.What is an Extension Function?An extension function is a function that is defined
4 min read
Kotlin genericsGenerics are one of Kotlin's most powerful features. They allow us to write flexible, reusable, and type-safe code. With generics, we can define classes, methods, and properties that work with different types while still maintaining compile-time type safety.What Are Generics?A generic type is a clas
6 min read
Exception Handling
Kotlin Exception Handling - try, catch, throw and finallyException handling is an important part of programming that helps us manage errors in our code without crashing the entire application. In this article, we will learn about exception handling in Kotlin, how to use try, catch, throw, and finally blocks, and understand different types of exceptions.Ko
5 min read
Kotlin Nested try block and multiple catch blockIn Kotlin, exception handling allows developers to manage errors gracefully and prevent application crashes. In this article, we will explore two advanced exception handling concepts in Kotlin:Nested try-catch blocksMultiple catch blocks, including how to simplify them using a when expression.Nested
3 min read
Null Safety