Science calculator based on Android

The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617332156
Link to the finished project codehttps://github.com/mzsama/My-project
The Aim of This AssignmentCreate a science calculator
MU STU ID and FZU STU ID21126739 832102125

I. PSP form

Personal Software Process StagesEstimated Time (minutes)Actual Time (minutes)
Planning300450
• Estimate300450
Development465480
• Analysis3060
• Design Spec6070
• Design Review3020
• Coding Standard1520
• Design6060
• Coding150120
• Code Review3040
• Test9090
Reporting7575
• Test Report3030
• Size Measurement1515
• Postmortem & Process Improvement Plan3030
Sum8401005

II. Introduction

In this blog post, I will provide a detailed guide on how to create a scientific calculator by using Android Studio and JAVA lauguege .

The scientific calculator implemented in this project includes the following features:

·Basic arithmetic operations (addition, subtraction, multiplication, division).
·Exponentiation (x^y) and factorial (x!) operations.
·Square (x^2) and cube (x^3) operations.
·Square root (√x) and natural logarithm (ln(x)) operations.
·Base-10 logarithm (log(x)) operation.
·Trigonometric functions (sin(x), cos(x), and tan(x)) operations.
·Input for the mathematical constants π (pi) and e (Euler’s number).
·Percentage calculation (%).

·Support for complex mathematical expressions, including the use of parentheses (()).

In this blog post, I will walk you through the process of creating this scientific calculator using Android Studio, covering the user interface design, button functionalities, error handling, and mathematical operations implementation. By the end of this tutorial, you will have a fully functional scientific calculator app for Android
Link to the finished project code:https://github.com/mzsama/My-project

III. Some ideas before making a project

What is Android studio and JAVA

Android Studio is an integrated development environment (IDE) specifically designed for developing Android applications. It offers a rich set of tools and features, including a code editor, debugger, interface designer, and emulator, to assist developers in creating high-quality Android apps. While Android Studio supports multiple programming languages, it is commonly used in conjunction with Java or Kotlin, which are the primary programming languages for Android applications.

Java is a widely used programming language that is particularly well-suited for Android development. It is an object-oriented language with a robust ecosystem and extensive community support. In Android development, Java is typically used to write the business logic and functionality of applications. Developers can use Java to write both the front-end and back-end code of Android apps, as well as the interface elements that interact with users.

Why use Android studio and JAVA?

Firstly, the combination of Android Studio and Java provides a powerful integrated development environment (IDE) specifically tailored for Android app development, including an excellent code editor, debugging tools, and UI design tools, significantly boosting development efficiency. Secondly, the Android platform boasts a wide user base, allowing apps to reach billions of Android device users worldwide. Additionally, Android Studio and Java are free and open-source, reducing development costs and making them suitable for developers of all levels, from beginners to professionals. Most importantly, the Android development community is vast and offers abundant documentation, tutorials, and support, addressing a variety of issues that developers may encounter during the development process. Compared to using C, Python, C++, or frontend development, the combination of Android Studio and Java is better suited for creating mobile applications on the Android platform, while also offering robust performance optimization, user interface design, and cross-platform capabilities.

IV. Design and implementation process

1.Creat a new Android studio project

Click on the “File” menu, select “New project,” and then choose the “Empty Activity” template in Android Studio. Configure project details.

2.Design the UI interface

· Use of ConstraintLayout: The root layout of the entire interface utilizes ConstraintLayout, a powerful tool in Android for creating flexible and responsive layouts.

· Setting Background Color: A RelativeLayout is used as a child layout within the ConstraintLayout, and it sets the background color to gray (#D3D3D3), providing an overall visual appeal.

· Text Input Field: An EditText element is used to accept user input. It has a specific ID (editView) and is configured with width, height, hint text, text size, and bottom alignment.

· Button Layout: A GridLayout is used to contain various buttons of the calculator. It defines the number of columns (4 columns) and rows (9 rows) and specifies the arrangement of buttons.

· Functional Buttons: Within the GridLayout, there are various buttons, including parentheses, delete, clear, square, cube, power, factorial, square root, natural logarithm, base-10 logarithm, sine, cosine, tangent, π, reciprocal, and percentage, among others. Each button has its respective text and click event.

· Result Display: At the bottom, there is a TextView element used to display calculation results or error messages. It is configured for bottom alignment, text size, and text color.

The code for the activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#D3D3D3"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp">

        <EditText
            android:id="@+id/editView"
            android:layout_width="360dp"
            android:layout_height="100dp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:background="@drawable/border"
            android:editable="false"
            android:gravity="bottom|right"
            android:hint="请输入..."
            android:textSize="24sp" />

        <GridLayout
            android:id="@+id/GridLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/editView"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="20dp"
            android:columnCount="4"
            android:orientation="horizontal"
            android:rowCount="9">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="clickButton"
                android:text="("
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="clickButton"
                android:text=")"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:layout_width="174dp"
                android:layout_height="wrap_content"
                android:layout_columnSpan="2"
                android:onClick="delete"
                android:text="DE"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="square"
                android:text="x^2"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="cube"
                android:text="x^3"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:id="@+id/button18"
                android:layout_width="175dp"
                android:layout_height="wrap_content"
                android:layout_columnSpan="2"
                android:onClick="empty"
                android:text="CL"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="power"
                android:text="x^y"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="factorial"
                android:text="x!"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="squareRoot"
                android:text=""
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="ln"
                android:text="ln"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="log"
                android:text="log"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="eulerNumber"
                android:text="e"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="sin"
                android:text="sin"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="cos"
                android:text="cos"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="tan"
                android:text="tan"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="pi"
                android:text="π"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="reciprocal"
                android:text="1/x"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="percentage"
                android:text="%"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="+"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="1"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="2"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="3"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="-"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="4"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="5"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="6"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="*"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="7"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="8"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="9"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="/"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="."
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="clickButton"
                android:text="0"
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

            <Button
                android:onClick="equal"
                android:text="="
                android:backgroundTint="#FFFFFF"
                android:textColor="#005BCF"
                android:textSize="24sp" />

        </GridLayout>

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dp"
            android:textColor="#FF0000"
            android:textSize="20sp" />
    </RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>


The code for border.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="#fff" />

    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
    <stroke
        android:width="1dp"
        android:color="#CdCdCd" />

    <gradient
        android:startColor="#E9E9E9"
        android:endColor="#FFFFFF"
        android:type="linear"
        android:angle="90"/>
   
    <corners android:radius="2dp" />

    <corners
        android:topRightRadius="2dp"
        android:bottomRightRadius="2dp"
        android:topLeftRadius="2dp"
        android:bottomLeftRadius="2dp"/>
</shape>

The UI is shown below:
在这里插入图片描述

3.Writing JAVA code:

Step 1: Import the corresponding package

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

Step 2: Define some variable declaration:
· This section imports the required libraries and declares some variables such as editText, text, str, and indexYN.

   private EditText editText;
   private TextView text;
   private StringBuilder str = new StringBuilder();
   private int indexYN = 0;

Step 3:Initialize the app’s main layout and UI elements
· In the onCreate method, the main layout of the app is set, and the editText and text variables are initialized.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText = findViewById(R.id.editView);
    text = findViewById(R.id.textView);
}

Step 4:Handle button clicks to input characters and perform calculations
· The following set of methods handle button click events, appending the text from the buttons to editText while updating the str string.

public void clickButton(View view) {
        Button button = (Button) view;
        editText.append(button.getText());
        str.append(button.getText());
    }

    public void empty(View view) {
        editText.setText(null);
        str.setLength(0);
    }

    public void delete(View view) {
        String nowText = editText.getText().toString();
        if (!nowText.isEmpty() && str.length()!=0) {
            editText.setText(nowText.substring(0, nowText.length() - 1));
            str.deleteCharAt(str.length() - 1);
        }
    }

    public void equal(View view) {
        indexYN = 0;
        estimate();
        if (indexYN == 0) {
            List<String> zhongZhui = zhuanZhongZhui(str.toString());
            List<String> houZhui = zhuanHouZhui(zhongZhui);
            editText.append("\n" + math(houZhui));
            str.setLength(0);
            str.append(math(houZhui));
        }
    }

    public void reciprocal(View view) {
        editText.append("1/");
        str.append("1/");
    }

    public void factorial(View view) {
        editText.append("!");
        str.append("!");
    }

    public void square(View view) {
        editText.append("^2");
        str.append("^2");
    }

    public void cube(View view) {
        editText.append("^3");
        str.append("^3");
    }

    public void power(View view) {
        editText.append("^");
        str.append("^");
    }

    public void squareRoot(View view) {
        editText.append("√");
        str.append("g");
    }

    public void eulerNumber(View view) {
        editText.append("e");
        str.append("e");
    }

    public void percentage(View view) {
        editText.append("%");
        str.append("*0.01");
    }

    public void pi(View view) {
        editText.append("π");
        str.append("p");
    }

    public void sin(View view) {
        editText.append("sin");
        str.append("s");
    }

    public void cos(View view) {
        editText.append("cos");
        str.append("c");
    }

    public void tan(View view) {
        editText.append("tan");
        str.append("t");
    }

    public void ln(View view) {
        editText.append("ln");
        str.append("l");
    }

    public void log(View view) {
        editText.append("log");
        str.append("o");
    }

Step 5:Convert infix expressions to token lists for further processing
· This method converts the user-entered infix expression string into a list of tokens. It iterates through the input string and splits it based on digits, operators, and special characters, then stores them in a list.

 private List<String> zhuanZhongZhui(String str) {
        int index = 0;
        List<String> list = new ArrayList<>();
        do {
            char ch = str.charAt(index);
            if ("+-*/^!logsct()".indexOf(ch) >= 0) {
                index++;
                list.add(ch + "");
            } else if (ch == 'e' || ch == 'p') {
                index++;
                list.add(ch + "");
            } else if ("0123456789".indexOf(ch) >= 0) {
                String str1 = "";
                while (index < str.length() && "0123456789.".indexOf(str.charAt(index)) >= 0) {
                    str1 += str.charAt(index);
                    index++;
                }
                list.add(str1);
            }
        } while (index < str.length());
        return list;
    }

Step 6:Convert infix to postfix notation for evaluation
· This method converts the token list of the infix expression into a token list of the postfix expression. It uses a stack data structure to manage the order of operators and returns the postfix expression.

  public List<String> zhuanHouZhui(List<String> list) {
        Stack<String> fuZhan = new Stack<>();
        List<String> list2 = new ArrayList<>();
        if (!list.isEmpty()) {
            for (String item : list) {
                if (isNumber(item)) {
                    list2.add(item);
                } else if (isOperator(item) && item.charAt(0) != '(') {
                    if (fuZhan.isEmpty()) {
                        fuZhan.push(item);
                    } else {
                        if (item.charAt(0) != ')') {
                            if (adv(fuZhan.peek()) <= adv(item)) {
                                fuZhan.push(item);
                            } else {
                                while (!fuZhan.isEmpty() && !("(".equals(fuZhan.peek()))) {
                                    if (adv(item) <= adv(fuZhan.peek())) {
                                        list2.add(fuZhan.pop());
                                    }
                                }
                                if (fuZhan.isEmpty() || fuZhan.peek().charAt(0) == '(') {
                                    fuZhan.push(item);
                                }
                            }
                        } else if (item.charAt(0) == ')') {
                            while (fuZhan.peek().charAt(0) != '(') {
                                list2.add(fuZhan.pop());
                            }
                            fuZhan.pop();
                        }
                    }
                }
            }
            while (!fuZhan.isEmpty()) {
                list2.add(fuZhan.pop());
            }
        } else {
            editText.setText("");
        }
        return list2;
    }

Step 7:Check if a token is an operator or number and determine operator precedence
· This section includes some utility methods to check whether a token is an operator or a number, and to determine the operator precedence.

public static boolean isOperator(String op) {
        return "0123456789.ep".indexOf(op.charAt(0)) == -1;
    }

    public static boolean isNumber(String num) {
        return "0123456789ep".indexOf(num.charAt(0)) >= 0;
    }

    public static int adv(String f) {
        int result = 0;
        switch (f) {
            case "+":
            case "-":
                result = 1;
                break;
            case "*":
            case "/":
                result = 2;
                break;
            case "^":
            case "!":
            case "g":
            case "l":
            case "o":
            case "s":
            case "c":
            case "t":
                result = 3;
                break;
        }
        return result;
    }

Step 8:Evaluate the postfix expression and perform mathematical calculations
· This method performs the calculation of the postfix expression, including addition, subtraction, multiplication, division, exponentiation, and other operations.

 public double math(List<String> list2) {
        Stack<String> stack = new Stack<>();
        for (String item : list2) {
            if (isNumber(item)) {
                if (item.charAt(0) == 'e') {
                    stack.push(String.valueOf(Math.E));
                } else if (item.charAt(0) == 'p') {
                    stack.push(String.valueOf(Math.PI));
                } else {
                    stack.push(item);
                }
            } else if (isOperator(item)) {
                double res = 0;
                if (item.equals("+")) {
                    double num2 = Double.parseDouble(stack.pop());
                    double num1 = Double.parseDouble(stack.pop());
                    res = num1 + num2;
                } else if (item.equals("-")) {
                    double num2 = Double.parseDouble(stack.pop());
                    double num1 = Double.parseDouble(stack.pop());
                    res = num1 - num2;
                } else if (item.equals("*")) {
                    double num2 = Double.parseDouble(stack.pop());
                    double num1 = Double.parseDouble(stack.pop());
                    res = num1 * num2;
                } else if (item.equals("/")) {
                    double num2 = Double.parseDouble(stack.pop());
                    double num1 = Double.parseDouble(stack.pop());
                    if (num2 != 0) {
                        res = num1 / num2;
                    } else {
                        editText.setText("除数不能为0");
                        indexYN = 1;
                    }
                } else if (item.equals("^")) {
                    double num2 = Double.parseDouble(stack.pop());
                    double num1 = Double.parseDouble(stack.pop());
                    res = Math.pow(num1, num2);
                } else if (item.equals("!")) {
                    double num1 = Double.parseDouble(stack.pop());
                    if (num1 == 0 || num1 == 1) {
                        res = 1;
                    } else if (num1 == (int) num1 && num1 > 1) {
                        int d = 1;
                        for (int j = (int) num1; j > 0; j--) {
                            d *= j;
                        }
                        res = d;
                    } else {
                        editText.setText("阶乘必须为自然数");
                        indexYN = 1;
                    }
                } else if (item.equals("g")) {
                    double num1 = Double.parseDouble(stack.pop());
                    res = Math.sqrt(num1);
                } else if (item.equals("l")) {
                    double num1 = Double.parseDouble(stack.pop());
                    if (num1 > 0) {
                        res = Math.log(num1);
                    } else {
                        editText.setText("ln的x必须大于0");
                        indexYN = 1;
                    }
                } else if (item.equals("o")) {
                    double num1 = Double.parseDouble(stack.pop());
                    if (num1 > 0) {
                        res = Math.log(num1) / Math.log(2);
                    } else {
                        editText.setText("log的x必须大于0");
                        indexYN = 1;
                    }
                } else if (item.equals("s")) {
                    double num1 = Double.parseDouble(stack.pop());
                    res = Math.sin(num1);
                } else if (item.equals("c")) {
                    double num1 = Double.parseDouble(stack.pop());
                    res = Math.cos(num1);
                } else if (item.equals("t")) {
                    double num1 = Double.parseDouble(stack.pop());
                    if (Math.cos(num1) != 0) {
                        res = Math.tan(num1);
                    } else {
                        editText.setText("tan的x不能为+-(π/2 + kπ)");
                        indexYN = 1;
                    }
                }
                stack.push(String.valueOf(res));
            }
        }
        if (indexYN == 0) {
            if (!stack.isEmpty()) {
                return Double.parseDouble(stack.pop());
            } else {
                return 0;
            }
        } else {
            return -999999;
        }
    }

Step 9:Alidate user input expressions for correctness and display error messages if needed
· This method is used to estimate whether the user’s input expression is valid, checking for errors within the expression.

public void estimate() {
        text.setText("");
        int i = 0;
        if (str.length() == 0) {
            text.setText("输入为空!");
            indexYN = 1;
        }
        if (str.length() == 1) {
            if ("0123456789ep".indexOf(str.charAt(0)) == -1) {
                text.setText("输入错误!");
                indexYN = 1;
            }
        }
        if (str.length() > 1) {
            for (i = 0; i < str.length() - 1; i++) {
                if ("losctg(0123456789ep".indexOf(str.charAt(0)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if ("+-*/".indexOf(str.charAt(i)) >= 0 && "0123456789losctg(ep".indexOf(str.charAt(i + 1)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if (str.charAt(i) == '.' && "0123456789".indexOf(str.charAt(i + 1)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if (str.charAt(i) == '!' && "+-*/^)".indexOf(str.charAt(i + 1)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if ("losctg".indexOf(str.charAt(i)) >= 0 && "0123456789(ep".indexOf(str.charAt(i + 1)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if (str.charAt(0) == '0' && str.charAt(1) == '0') {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if (i >= 1 && str.charAt(i) == '0') {
                    int m = i;
                    int n = i;
                    int is = 0;
                    if ("0123456789.".indexOf(str.charAt(m - 1)) == -1 && "+-*/.!^)".indexOf(str.charAt(i + 1)) == -1) {
                        text.setText("输入错误!");
                        indexYN = 1;
                    }
                    if (str.charAt(m - 1) == '.' && "0123456789+-*/.^)".indexOf(str.charAt(i + 1)) == -1) {
                        text.setText("输入错误!");
                        indexYN = 1;
                    }
                    n -= 1;
                    while (n > 0) {
                        if ("(+-*/^glosct".indexOf(str.charAt(n)) >= 0) {
                            break;
                        }
                        if (str.charAt(n) == '.') {
                            is++;
                        }
                        n--;
                    }
                    if ((is == 0 && str.charAt(n) == '0') || "0123456789+-*/.!^)".indexOf(str.charAt(i + 1)) == -1) {
                        text.setText("输入错误!");
                        indexYN = 1;
                    }
                    if (is == 1 && "0123456789+-*/.^)".indexOf(str.charAt(i + 1)) == -1) {
                        text.setText("输入错误!");
                        indexYN = 1;
                    }
                    if (is > 1) {
                        text.setText("输入错误!");
                        indexYN = 1;
                    }
                }
                if ("123456789".indexOf(str.charAt(i)) >= 0 && "0123456789+-*/.!^)".indexOf(str.charAt(i + 1)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if (str.charAt(i) == '(' && "0123456789locstg()ep".indexOf(str.charAt(i + 1)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if (str.charAt(i) == ')' && "+-*/!^)".indexOf(str.charAt(i + 1)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if ("0123456789!)ep".indexOf(str.charAt(str.length() - 1)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
                if (i > 2 && str.charAt(i) == '.') {
                    int n = i - 1;
                    int is = 0;
                    while (n > 0) {
                        if ("(+-*/^glosct".indexOf(str.charAt(n)) >= 0) {
                            break;
                        }
                        if (str.charAt(n) == '.') {
                            is++;
                        }
                        n--;
                    }
                    if (is > 0) {
                        text.setText("输入错误!");
                        indexYN = 1;
                    }
                }
                if ("ep".indexOf(str.charAt(i)) >= 0 && "+-*/^)".indexOf(str.charAt(i + 1)) == -1) {
                    text.setText("输入错误!");
                    indexYN = 1;
                }
            }
        }
    }

V.The flow chat

When the user enters a mathematical expression in the EditText, and they click the “=” button, the following steps are taken:

· First, the estimate() method is called to validate the input expression. This method checks whether the characters in the expression comply with the rules of a mathematical expression. If any errors are found, it sets an error flag (indexYN) and displays an error message in the TextView.

· If the input expression passes validation, the next steps involve calculating the expression’s value:

a. The zhuanZhongZhui() method is called to convert the infix expression into a list containing operands, operators, and other mathematical functions.

b. The zhuanHouZhui() method is then used to convert the infix expression list into a postfix expression (Reverse Polish Notation or RPN) list.

c. The math() method is employed to calculate the value of the postfix expression list.

· The math() method uses a stack data structure to compute the value of the postfix expression. It iterates through each element in the postfix expression list. If an element is an operand, it is pushed onto the stack. If it’s an operator, the method pops the required number of operands, performs the corresponding operation, and pushes the result back onto the stack. This process continues until the entire postfix expression is evaluated.

· The final result is popped from the stack and returned. If any errors occur during the calculation process, such as division by zero or invalid input, the error flag (indexYN) is set, and an error message is displayed. The code then waits for the user to input another mathematical expression.
在这里插入图片描述

VI.The Final result show

(i)Normal calculation

Normal

(ii)Error handling

Error calculation

VII.Evaluation

Advantages:

· Scientific Calculation Capability: This calculator provides a wide range of scientific calculation functions, including common mathematical operations, trigonometric functions, logarithms, exponentials, factorials, and more. This makes it suitable for various mathematical and scientific computing needs.

· User-Friendly Interface: The application’s interface is designed intuitively, allowing users to input numbers, operators, and functions by simply clicking buttons. This reduces the learning curve and makes the calculator easy to use.

· Error Handling: The calculator includes error-handling features. For example, when dividing by zero or inputting an invalid expression, it displays error messages to users and sets an error flag. This enhances the user experience by informing users of issues.

· Conversion to Reverse Polish Notation (RPN): The calculator converts the input infix expressions into reverse Polish notation (RPN), which is easier to compute. This can reduce the likelihood of calculation errors and improve accuracy.

Limitations:

· Limited Interface: While the interface is user-friendly, this calculator’s functionality is limited to scientific calculations. It may not be suitable for advanced mathematical tasks or symbolic algebraic manipulations.

· Brief Error Messages: Although the calculator can detect errors and display error messages, these messages are often simplistic and may not provide detailed error information, making it challenging for users to understand the specific reasons for the errors.

· No Support for Parentheses Priority: The calculator does not consider the impact of parentheses on operator precedence when evaluating expressions. This may lead to unexpected results for certain expressions.

· Functional Constraints: While it offers some common mathematical functions, this calculator may not meet the requirements of advanced mathematical tasks such as calculus or linear algebra.

VIII.Summary

When developing this scientific calculator, I learned a lot of important knowledge and skills related to Android app development:

· Android Studio Development: While developing the scientific calculator, I learned how to use Android Studio to create Android applications. This includes fundamental skills such as creating user interfaces, adding buttons and text fields, and managing layouts.

· Java Programming: Android applications are primarily developed using the Java programming language. In this project, I deepened my understanding of Java programming, including how to handle strings, lists, arrays, and implement logic and algorithms.

· User Interface Design: I learned how to design user-friendly interfaces, including placing buttons and text fields on the screen for users to easily input and view mathematical expressions and calculation results.

· Learning from CSDN: During the project development process, I may encounter some issues that require finding solutions. I learned how to use online resources like CSDN to search for articles and tutorials on Android development to solve various problems.

· Application of GitHub: I learned how to use GitHub to manage my project code. I can upload the project to GitHub for backup and version control. Additionally, I can collaborate with other developers and invite them to contribute to my project.

· Algorithms and Mathematical Knowledge: Developing a scientific calculator requires some mathematical and algorithmic knowledge. I learned how to process infix expressions, convert them to postfix expressions, and perform calculations. This deepened my understanding of some concepts in computer science.

· Error Handling: In the application, I learned how to handle user input errors and other exceptional situations to provide a user-friendly experience and avoid application crashes.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值