EE308FZ Lab_1 Practical Android Studio calculator

EE308FZ Lab_1 Practical Android Studio calculator

The Link Your Class2301-MUSE Community
The Link of Requirement of This AssignmentSoftware Engineering Practice First Assignment
The Link of The Code of This ProjectEE308FZ Lab_1 Practical Android Studio calculator
Software Engineering Practice First AssignmentCreate a calculator with a visual interface and write a blog to record your work content and process.
MU STU ID and FZU STU ID21126569_832102101

Catalogue

  • Ⅰ. PSP form
  • Ⅱ. Introduction
  • Ⅲ. Description of problem-solving ideas.
  • Ⅳ. Design and implementation process
  • Ⅴ. Code description
      1. User Interface Design
      • Integrated layout
      • Buttons styling design
      • Dynamic buttons design
      1. Main activity class
      • Dynamic buttons design
      • Initialization of variables and buttons
      • Button click event handling
      • Set the decimal digits
      • Clipboard Copy action
      1. Handle User Input
      • Number Button Handling
      • Operator Button Handling
      • Trigonometric Button Handling
      • Other Button Handling
      1. Testing and Debugging
  • Ⅵ. Final result display
  • Ⅶ. Assignment Summary

Ⅰ. PSP form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning4530
• Estimate4530
Development395450
• Analysis3030
• Design Spec1525
• Design Review1520
• Coding Standard1520
• Design6060
• Coding150165
• Code Review5050
• Test6080
Reporting6080
• Test Repor1010
• Size Measurement1010
• Postmortem & Process Improvement Plan4060
Sum500560

Ⅱ. Introduction

This blog will guide you through the process of creating a personalized Android calculator application utilizing the Android studio IDE, which covers fundamental mathematical operations, UI design and the front-end and back-end interactions.
Particularly, this blog provides insights into implementing diverse functions, for an instance, addition, subtraction, multiplication, division, power, reverse and basic trigonometric functions. The scientific calculator implemented in this project includes the following features:
· Basic arithmetic operations (addition, subtraction, multiplication, division).
· Exponentiation (x^y) operations.
· Trigonometric functions (sin(x), cos(x), and tan(x)) operations.
· Percentage calculation (%) and Reversing calculation (+/-).
· Other innovative features: Calculation result precision selection and Clipboard Copy action.
Link to the finished project code:EE308FZ Lab_1 Practical Android Studio calculator

Ⅲ. Description of problem-solving ideas.

Technology and tool selection

The Android operating system is one of the most popular mobile operating systems. Compared with web calculators or WeChat mini program calculators, Android calculators have stronger practicability. Additionally, Android development is a broad skill, and mastering it can provide a solid foundation for a later career.

Android Stuido

Android Studio is a powerful Integrated development environment (IDE) specifically tailored for Android application development. It includes excellent code editors, debugging tools, and UI design tools that significantly improve development efficiency. Additionally, Android is a massive platform with billions of device users around the world. This means that applications developed have the opportunity to reach a broad global user base. This broad user base can help your app get more downloads and usage, contributing to the success and popularity of your app.

Critical Thinking Process

Through the Critical Thinking Process, I constructed the blueprint of the project. Android calculators need user-friendly UI design, efficient and accurate calculations. In order to improve the function of the calculator, I added more complex calculation formulas to effectively implementing complex mathematical functions, and introduced the accuracy selection of calculation results, results copy clipboard functions.

Adjustments and Improvements

During the development of the Android calculator app, I continuously make adjustments and improvements to ensure that the user experience is always at its best. I actively collect user feedback, optimize performance, improve interface design, add new features, and ensure application security and stability. Our goal is to continuously meet user needs, adapt to technological changes, and provide a high quality computing experience.

Ⅳ. Design and implementation process

The design and implementation process of the calculator application is a crucial aspect of its development. It encompasses how the code is organized and the flowchart of key functions. Here, we delve into the architectural and structural aspects of the calculator, shedding light on the thought process behind its creation.
User Interface (UI): The user interface component handles the presentation layer of the calculator. It defines the layout, appearance, and interaction elements, making the application visually appealing and user-friendly.
Core Calculator Logic: The core calculator logic constitutes the computational engine that performs arithmetic operations, trigonometric calculations, and other mathematical tasks. It encapsulates the algorithms and data structures required for accurate calculations.
User Input Handling: This module manages user interactions, capturing input from button clicks, touch events, and keyboard input. It ensures that user commands are correctly interpreted and processed.
Error Handling: Error handling mechanisms are integrated to gracefully manage exceptional scenarios, such as division by zero or invalid input. Robust error handling enhances the calculator’s reliability and user experience.

To gain insights into how the calculator processes user inputs and executes mathematical operations, we can visualize its key functions through flowcharts. These flowcharts serve as valuable documentation and aid in comprehending the logic behind each operation.flow chart

Ⅴ. Code description

This project mainly contains five Java files and several xml auxiliary files. In this section, I’ll delve into the key aspects of the critical codes. Understanding the design decisions, implementation logic, and underlying concepts is crucial for gaining insights into how the calculator functions.

1. User Interface Design

Integrated layout

The file defines a layout including the calculator interface. The interface is divided into top and bottom two parts, the top display calculation results and accuracy, the bottom contains the number buttons, operator buttons and other function buttons, through the grid layout of buttons, so as to achieve the calculator UI layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout
    // Relative layout codes that display calculation results and accuracy
    </RelativeLayout>
 
    <GridLayout
    // Grid layout codes that display buttons
    </GridLayout>
</RelativeLayout>
Buttons styling design

Place the style and shape definitions in XML files. Helps improve code maintainability, readability, reusability, and ease of maintenance and update, while reducing code redundancy.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid
    <corners
</shape>
Dynamic buttons design

Touch event listener: handles the user’s touch actions on the screen, including not only clicking, but also swiping, dragging, zooming, and other touch gestures. Hence, we can dynamically resize the buttons by monitoring their status.
The interactive effect of button pressing and automatically shrinking can improve user interface interactivity, visual feedback and user experience. This design choice often makes the user interface more appealing, making it easier for users to understand and interact with the application.

public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setScaleX(0.9f);
                view.setScaleY(0.9f);
                break;
            case MotionEvent.ACTION_UP:
                view.setScaleX(1);
                view.setScaleY(1);
                break;
            default:
        }
        return false;
    }

The final User Interface outcome is as follows:
在这里插入图片描述

2. Main activity class

Initialization of variables and buttons

The onCreate method is the method called when the activity is created to set the layout and initialization of the activity. And the init method takes care of further initialization, including setting up the touch event listener, creating the Calculator object (to perform the calculation logic), and getting and setting the TextView control on the interface.

Button click event handling

The onClick method handles what the user does when he clicks individual buttons.
Based on the button ID, use the switch statement to determine which button the user clicked, and call the appropriate method in the Calculator class to handle the button click event.

// Initialization the listener in init function
btn.setOnClickListener(this);
        
public void onClick(View view) {
        // Gets the text content of the current TextView
        String numberText = txContent.getText().toString();
        switch (view.getId()) {
            case R.id.btn_clear:
                numberText = calculator.clickOperator(CalculatorOperator.CLEAR, numberText);
                break;
            case ......}
        txContent.setText(numberText);
    }
                
Set the decimal digits

Display a text box when users click on precision (txPrecision), set will trigger the operation of decimal digits. In click event processing, check the current precision value and reset the precision to 0 if it is greater than 8, otherwise increment the precision value and apply it to the Calculator object. Update the text box content showing precision.

txPrecision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(precision > 8)
                    precision = 0;
                precision++;
                calculator.setDecimalPlaces(precision);
//                txPrecision.setText(precision);
                txPrecision.setText(String.valueOf(precision));
            }
        });
Clipboard Copy action

When the user clicks the Copy button, this action copies the text content currently displayed to the clipboard. Copy the text to the clipboard by getting the ClipboardManager and creating a ClipData object. At the same time, a short notification message is displayed informing the user that the text has been copied to the clipboard.

				// Get the clipboard manager
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // Create a ClipData object that contains the text to copy
                ClipData clipData = ClipData.newPlainText("text", numberText);
                // 将ClipData对象复制到剪贴板
                clipboardManager.setPrimaryClip(clipData);
                // Prompts the user that the text has been copied to the clipboard
                Toast.makeText(this, "文本已复制到剪贴板", Toast.LENGTH_SHORT).show();
                break;

3. Handle User Input:

Number Button Handling

The function of clickCode is to handle the click event of the number button. It determines whether it is dealing with the first or second operand based on the current operator, adds the number clicked by the user to the text of the current number, and attempts to convert it to type Double for numerical computation. It then determines whether the current number is the first or second number based on the action symbol (+, -, ×, ÷), and builds a display string that includes the number and the operator, which is finally returned to update the calculator’s display.

// Handle numeric button click events
    public String clickCode(CalculatorCode code) {
        Double number = null;
        // Determine whether the first or second operand is being processed based on the current operator
        if (this.operator == null)
            number = firNum;
        else
            number = secNum;

        // Adds the number clicked by the user to the current number text and attempts to convert it to type Double for numerical calculation.
        String numberText = currentNumberText + code.getNumber();
        try {
            number = Double.parseDouble(numberText);
        }catch (NumberFormatException e) {
            numberText = currentNumberText;
        }
        // Use the operation sign (+-x÷) to determine whether the current number is the first or second number
        if (operator == null)
            firNum = number;
        else
            secNum = number;

        StringBuilder builder = new StringBuilder();

        if (operator == null) {
            builder.append(numberText);
        }
        // Add an operator and a second number if one currently exists
        else  {
            builder.append(doubleWithInt(firNum));
            builder.append(operator.getOperator());
            builder.append(numberText);
        }
        currentNumberText = numberText;
        // 返回需要显示的字符串
        return builder.toString();
    }
Operator Button Handling

This code is the key part of the calculator class that handles the clear state, operator button click events, and performing math operations.
The clickOperator() function then handles the click event of the operator button, performing operations such as clear, inverse, percent, trigonometric, four-rule, and exponentiation depending on the operator.
Finally, the equals() function performs a mathematical operation, calculates the result based on the current operator and operand, and updates the state of the calculator.
These functions together implement the basic operation logic of the calculator.

    // Handle operator button click events, such as addition, subtraction, etc.
    // Depending on the operator clicked, perform different operations, such as clear, invert, add a decimal point, perform calculations, etc    public String clickOperator(CalculatorOperator operator, String numberText) {
        String result = "";
        switch (operator) {
            case CLEAR:
                clear();
                result = "";
                break;
            case REVERSE:
                result = reverse();
                break;
            case PERCENT:
                result = percent();
                break;
            case SIN:
                result = calculateSin();
                break;
            case COS:
                result = calculateCos();
                break;
            case TAN:
                result = calculateTan();
                break;

            case DIVISION:
            case MULTIPLICATION:
            case SUBTRACTION:
            case ADDITION:
            case POWER:
                char inputOperator = operator.getOperator();
                if (this.operator == null) {
                    result = numberText + inputOperator;
                } else {
                    char lastOperator = numberText.charAt(numberText
                            .length() - 1);
                    result = equals(numberText);
                    if (this.operator == null) {
                        result += inputOperator;
                    }else {
                        result = result.replace(lastOperator, inputOperator);
                    }
                }
                currentNumberText = "";
                this.operator = operator;
                break;
            case EQUAlS:
                result = equals(numberText);
                break;
        }

        return result;
    }

private String equals(String numberText) {
        double result = 0.0;
        if(secNum.equals(0.0) && operator.getOperator() == '×'){
            result = 0.0;
            firNum = result;
            operator = null;
            secNum = 0.0;
            currentNumberText = doubleWithInt(result);
            return doubleWithInt(firNum);
        }
        // If the second tree entered by no operator directly equals/is 0, it is returned directly
        // 这里有点小问题,如果是乘以0就不对了,所以先研究乘以0的情况
        if (this.operator == null || secNum.equals(0.0)) {
            return numberText;
        }

        switch (operator) {
            case DIVISION:
                result = firNum / secNum;
                break;
            case MULTIPLICATION:
                result = firNum * secNum;
                break;
            case SUBTRACTION:
                result = firNum - secNum;
                break;
            case ADDITION:
                result = firNum + secNum;
                break;
            case POWER:
                result = Math.pow(firNum, secNum);
        }

//        firNum = result;
        firNum = Double.valueOf(formatResult(result));
        operator = null;
        secNum = 0.0;
//        currentNumberText = formatResult(result); // Format the result
        currentNumberText = doubleWithInt(result);
        return doubleWithInt(firNum);
    }
Trigonometric Button Handling

This section of code is responsible for calculating the values of the trigonometric functions sin, cos, and tan, formatting the result as a string, and then clearing the current operator. This ensures that the correct trigonometric results are displayed on the calculator.

    private String calculateSin() {
        firNum = Math.sin(Math.toRadians(firNum));
        firNum = Double.valueOf(formatResult(firNum));
        operator = null;
        return doubleWithInt(firNum);
    }
    private String calculateCos() {
        firNum = Math.cos(Math.toRadians(firNum));
        firNum = Double.valueOf(formatResult(firNum));
        operator = null;
        return doubleWithInt(firNum);
    }

    private String calculateTan() {
        firNum = Math.tan(Math.toRadians(firNum));
        firNum = Double.valueOf(formatResult(firNum));
        operator = null;
        return doubleWithInt(firNum);
    }
Other Button Handling

The clear() function is used to reset the state of the calculator to its initial value, including emptying operands and operators, and emptying the current numeric text.
The inverse() function, it changes the first operand stored (firNum) to its opposite, that is, a positive number becomes a negative number or a negative number becomes a positive number.
The percent() function divides the first stored operand (firNum) by 100 to convert it to a percentage.

	// Used to clear the state of the calculator and reset all variables to their initial values
    private void clear() {
        firNum = 0.0;
        secNum = 0.0;
        operator = null;
        currentNumberText = "";
    }
	private String reverse() {
        firNum = -firNum;
        operator = null;
        return doubleWithInt(firNum);
    }


    private String percent() {
        firNum /= 100;
        operator = null;
        return doubleWithInt(firNum);
    }
Set decimal places

setDecimalPlaces function is used to set the number of decimal places selected by the user. The default number is 6. The formatResult function is used to format the result according to the number of decimal places selected by the user, and is formatted using DecimalFormat. Together, these methods realize the function of controllable display of decimal places.

	// 将一个 Double 类型的数转换为字符串,并根据是否可以转换为整数来决定返回的字符串形式。
    // 如果可以转换为整数,返回整数形式的字符串,否则返回原始的双精度浮点数形式的字符串。
    // 这种操作可能用于确保显示数字时不显示多余的小数位。
    private String doubleWithInt(Double number) {
        boolean flag = number.longValue() == number;
        if (flag) {
            return String.valueOf(number.longValue());
        }
        return number.toString();
    }
    // 额外功能:实现可控的小数位选择
    private int decimalPlaces = 6; // 用户选择的小数位数,默认为6位

    // 设置小数位数
    public void setDecimalPlaces(int decimalPlaces) {
        this.decimalPlaces = decimalPlaces;
    }
    private String formatResult(double result) {
        // 构造格式化字符串,根据用户选择的小数位数来设置格式
        StringBuilder formatBuilder = new StringBuilder("#.");
        for (int i = 0; i < decimalPlaces; i++) {
            formatBuilder.append("#");
        }
        String formatPattern = formatBuilder.toString();

        // 使用 DecimalFormat 格式化结果
        DecimalFormat decimalFormat = new DecimalFormat(formatPattern);
        return decimalFormat.format(result);
    }

4. Testing, Debugging and Error Handling

In software development, testing and debugging are critical steps to ensure the accuracy and stability of a calculator application. By thoroughly testing a wide range of mathematical calculations and user input situations, we can ensure that the calculator works correctly in all situations
In order to ensure that the calculator can perform accurate mathematical calculations, I have conducted thorough testing, which includes testing basic arithmetic operations (addition, subtraction, multiplication, division) as well as special functions (such as trigonometric functions, percentages, etc.).
Users may enter invalid expressions or operators, such as dividing by zero, invalid operator combinations, and so on. When user input is invalid, the user is alerted to an error by toasting.

Ⅵ. Final result display

To conduct a comprehensive evaluation of the developed Android calculator, I performed extensive testing on virtual machine, capturing real-time demonstrations to visually display its capabilities.
After rigorous testing and evaluation, the application software exhibits remarkable proficiency in handling a wide array of fundamental mathematical calculations, showcasing its exceptional accuracy in performing addition, subtraction, multiplication, and division operations. It not only excels in addressing basic arithmetic needs but also caters to more advanced requirements. The Android calculator seamlessly executes power operations, enabling users to calculate power efficiently. Additionally, it seamlessly handles complex mathematical tasks such as three-piece function calculations, demonstrating its versatility and capacity to accommodate various mathematical scenarios.
Furthermore, the calculator’s utility extends beyond mathematical operations, offering convenient features such as a copy function, enabling users to replicate results effortlessly. Its precision extends to decimal place selection, allowing users to tailor the level of precision to their specific needs. These additional functionalities enhance the calculator’s overall appeal and user-friendliness, making it a valuable tool for both basic and advanced mathematical tasks.

The final demonstration of the Android calculator is as follows:

finalResult

Ⅶ. Assignment Summary

In this concise summary, I reflect upon the entire journey of conceptualizing, designing, implementing, and presenting my Android Calculator project. It all began with a critical examination of the problem, leading to a solid foundation for solution development. Throughout the design and implementation phases, I prioritized well-structured code and clear functional flowcharts to ensure logical coherence and ease of maintenance. This reflection highlights the core project concepts, offering a comprehensive understanding of the calculator’s functionality. By showcasing screenshots and live demonstrations, I vividly demonstrate the calculator’s proficiency in basic arithmetic, trigonometric functions, and exponentiation. In conclusion, I contemplate the challenges faced, the knowledge gained, and potential enhancements, providing valuable insights for personal and academic growth in software development.

在这里插入图片描述

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值