How to Make a Scientific Calculator app for Android

How to Make a Scientific Calculator app for Android [Code Included]

Creating a scientific Android app involves designing a user interface (UI) and implementing functionality for scientific calculations, such as arithmetic operations, trigonometric functions, logarithms, exponentials, etc. Below is an example of a simple scientific calculator app in Android using Java and Android Studio.

Steps to Create the App:

  1. Set up an Android Studio project.
  2. Design the UI using XML.
  3. Implement the logic in Java.

1. XML Layout (UI Design)

Create a activity_main.xml file in the res/layout folder:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <!-- Display for input and output -->
    <EditText
        android:id="@+id/display"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:inputType="none"
        android:focusable="false"
        android:clickable="false"
        android:text="0"
        android:gravity="end"
        android:background="@android:color/transparent"
        android:padding="8dp" />

    <!-- Buttons for scientific operations -->
    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="4"
        android:rowCount="5">

        <!-- Row 1 -->
        <Button android:text="sin" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="cos" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="tan" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="√" android:onClick="onButtonClick" android:layout_columnWeight="1" />

        <!-- Row 2 -->
        <Button android:text="log" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="ln" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="^" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="C" android:onClick="onButtonClick" android:layout_columnWeight="1" />

        <!-- Row 3 -->
        <Button android:text="7" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="8" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="9" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="/" android:onClick="onButtonClick" android:layout_columnWeight="1" />

        <!-- Row 4 -->
        <Button android:text="4" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="5" android:onButtonClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="6" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="*" android:onClick="onButtonClick" android:layout_columnWeight="1" />

        <!-- Row 5 -->
        <Button android:text="1" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="2" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="3" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="-" android:onClick="onButtonClick" android:layout_columnWeight="1" />

        <!-- Row 6 -->
        <Button android:text="0" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="." android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="=" android:onClick="onButtonClick" android:layout_columnWeight="1" />
        <Button android:text="+" android:onClick="onButtonClick" android:layout_columnWeight="1" />
    </GridLayout>
</LinearLayout>

2. Java Code (Logic)

Create the MainActivity.java file in the java/com/example/scientificcalculator folder:

package com.example.scientificcalculator;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText display;
    private String input = "";
    private boolean isResultDisplayed = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        display = findViewById(R.id.display);
    }

    // Handle button clicks
    public void onButtonClick(View view) {
        String buttonText = ((android.widget.Button) view).getText().toString();

        switch (buttonText) {
            case "C":
                input = "";
                break;
            case "=":
                calculateResult();
                isResultDisplayed = true;
                break;
            case "√":
                input = String.valueOf(Math.sqrt(Double.parseDouble(input)));
                break;
            case "sin":
                input = String.valueOf(Math.sin(Math.toRadians(Double.parseDouble(input))));
                break;
            case "cos":
                input = String.valueOf(Math.cos(Math.toRadians(Double.parseDouble(input))));
                break;
            case "tan":
                input = String.valueOf(Math.tan(Math.toRadians(Double.parseDouble(input))));
                break;
            case "log":
                input = String.valueOf(Math.log10(Double.parseDouble(input)));
                break;
            case "ln":
                input = String.valueOf(Math.log(Double.parseDouble(input)));
                break;
            case "^":
                input += "^";
                break;
            default:
                if (isResultDisplayed && !buttonText.matches("[0-9]")) {
                    input = "";
                }
                input += buttonText;
                isResultDisplayed = false;
                break;
        }

        display.setText(input);
    }

    // Calculate the result
    private void calculateResult() {
        try {
            // Handle exponentiation (^)
            if (input.contains("^")) {
                String[] parts = input.split("\\^");
                double base = Double.parseDouble(parts[0]);
                double exponent = Double.parseDouble(parts[1]);
                input = String.valueOf(Math.pow(base, exponent));
            } else {
                // Evaluate other expressions
                input = String.valueOf(eval(input));
            }
        } catch (Exception e) {
            input = "Error";
        }
    }

    // Evaluate mathematical expressions
    private double eval(String expression) {
        return new Object() {
            int pos = -1, ch;

            void nextChar() {
                ch = (++pos < expression.length()) ? expression.charAt(pos) : -1;
            }

            boolean eat(int charToEat) {
                while (ch == ' ') nextChar();
                if (ch == charToEat) {
                    nextChar();
                    return true;
                }
                return false;
            }

            double parse() {
                nextChar();
                double x = parseExpression();
                if (pos < expression.length()) throw new RuntimeException("Unexpected: " + (char) ch);
                return x;
            }

            double parseExpression() {
                double x = parseTerm();
                for (; ; ) {
                    if (eat('+')) x += parseTerm(); // addition
                    else if (eat('-')) x -= parseTerm(); // subtraction
                    else return x;
                }
            }

            double parseTerm() {
                double x = parseFactor();
                for (; ; ) {
                    if (eat('*')) x *= parseFactor(); // multiplication
                    else if (eat('/')) x /= parseFactor(); // division
                    else return x;
                }
            }

            double parseFactor() {
                if (eat('+')) return parseFactor(); // unary plus
                if (eat('-')) return -parseFactor(); // unary minus

                double x;
                int startPos = this.pos;
                if (eat('(')) { // parentheses
                    x = parseExpression();
                    eat(')');
                } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
                    while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
                    x = Double.parseDouble(expression.substring(startPos, this.pos));
                } else {
                    throw new RuntimeException("Unexpected: " + (char) ch);
                }

                return x;
            }
        }.parse();
    }
}

3. Features of the App:

  • Basic arithmetic operations (+-*/).
  • Scientific functions (sincostanlogln^).
  • Clear button (C) to reset the input.
  • Real-time display of input and results.

4. Run the App:

  1. Open the project in Android Studio.
  2. Connect an Android device or use an emulator.
  3. Click Run to build and deploy the app.

This is a basic implementation. You can enhance it further by adding more features like history, themes, or unit conversions. Let me know if you need help with any specific feature! 

Leave a Reply

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