当前位置: 首页 > article >正文

Android实现简易计算器

<?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">

    <EditText
        android:id="@+id/result_display"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number|numberDecimal"
        android:editable="false"
        android:gravity="end"
        android:padding="16dp"
        android:textSize="24sp" />

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/btn_7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="7"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="8"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_9"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="9"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_divide"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="/"
                android:onClick="onButtonClick" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/btn_4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="4"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="5"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="6"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_multiply"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="*"
                android:onClick="onButtonClick" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/btn_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="2"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="3"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_minus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="-"
                android:onClick="onButtonClick" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/btn_0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="0"
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_dot"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="."
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_equal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="="
                android:onClick="onButtonClick" />

            <Button
                android:id="@+id/btn_plus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="+"
                android:onClick="onButtonClick" />
        </TableRow>

    </TableLayout>
</LinearLayout>

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText resultDisplay;
    private String currentOperator = "";
    private double num1 = 0;
    private double num2 = 0;
    private boolean operatorEntered = false;

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

        resultDisplay = findViewById(R.id.result_display);
    }

    public void onButtonClick(View view) {
        Button button = (Button) view;
        String buttonText = button.getText().toString();

        if (buttonText.matches("[0-9.]")) {
            if (operatorEntered) {
                resultDisplay.setText(buttonText);
                operatorEntered = false;
            } else {
                resultDisplay.setText(resultDisplay.getText() + buttonText);
            }
        } else if (buttonText.matches("[+\\-*/]")) {
            num1 = Double.parseDouble(resultDisplay.getText().toString());
            currentOperator = buttonText;
            operatorEntered = true;
        } else if (buttonText.equals("=")) {
            num2 = Double.parseDouble(resultDisplay.getText().toString());
            double result = performCalculation(num1, num2, currentOperator);
            resultDisplay.setText(String.valueOf(result));
            operatorEntered = false;
        } else {
            Toast.makeText(this, "Invalid operation", Toast.LENGTH_SHORT).show();
        }
    }

    private double performCalculation(double num1, double num2, String operator) {
        switch (operator) {
            case "+":
                return num1 + num2;
            case "-":
                return num1 - num2;
            case "*":
                return num1 * num2;
            case "/":
                if (num2 != 0) {
                    return num1 / num2;
                } else {
                    Toast.makeText(this, "Division by zero", Toast.LENGTH_SHORT).show();
                    return 0;
                }
            default:
                return 0;
        }
    }
}
 

相关文章:

Android实现简易计算器

<?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" and…...

PHP 在 if 判断时由于运算符优先级导致 false 的问题

首先来看一段代码&#xff1a; $price 187.50;if (!is_numeric($price) || $price < 0 || ($price * 100 > 1000000)) {echo "价格错误&#xff1a;$price\n"; } else {echo "价格正确&#xff1a;$price\n"; }乍一看是不是认为并没有什么问题&…...

【分布式】如何使用RocketMQ实现下单-库存-支付这个场景的分布式事务问题

在 下单-库存-支付 场景中&#xff0c;通过消息队列实现最终一致性&#xff0c;需保证三个微服务的操作最终一致&#xff0c;且在支付失败或库存不足时触发回滚补偿。以下是具体实现方案&#xff1a; 1. 整体流程设计 正常流程&#xff08;成功场景&#xff09; 订单服务 创建…...

手写一些常见算法

手写一些常见算法 快速排序归并排序Dijkstra自定义排序交替打印0和1冒泡排序插入排序堆排序 快速排序 public class Main {public static void main(String[] args) {int nums[] {1,3,2,5,4,6,8,7,9};quickSort(nums,0,nums.length - 1);}private static void quickSort(int[…...

使用DeepSeek完成一个简单嵌入式开发

开启DeepSeek对话 请帮我使用Altium Designer设计原理图、PCB&#xff0c;使用keil完成代码编写&#xff1b;要求&#xff1a;使用stm32F103RCT6为主控芯片&#xff0c;控制3个流水灯的原理图 这里需要注意&#xff0c;每次DeepSeek的回答都不太一样。 DeepSeek回答 以下是使…...

每日一题之储存晶体

问题描述 威慑纪元 2230 年&#xff0c;人类联邦在与三体文明的对抗中&#xff0c;为了强化飞船的能源储备&#xff0c;决定收集能量晶体。飞船的储存空间呈矩形&#xff0c;边长分别为 a 和 b。对于一个能量晶体&#xff0c;只有当它的长度小于或等于存储空间的对角线长度时&…...

关于我和快速幂的事()

我之前只会这样的(dfs&#xff09;&#xff1a; 不懂下面这种写法的具体逻辑&#xff1a; 看完下面的推理&#xff0c;再转转我聪明的小老戴&#xff1a; 法一中&#xff1a;把2^11看成(2^5)^2 法二中&#xff1a;把2^11看成(2^2)^5...

【鸿蒙开发】Hi3861学习笔记- GPIO之直流电机

00. 目录 文章目录 00. 目录01. GPIO概述02. 直流电机概述03. ULN2003模块概述04. 硬件设计05. 软件设计06. 实验现象07. 附录 01. GPIO概述 GPIO&#xff08;General-purpose input/output&#xff09;即通用型输入输出。通常&#xff0c;GPIO控制器通过分组的方式管理所有GP…...

mapbox高阶,结合threejs(threebox)添加extrusion挤出几何体,并添加侧面窗户贴图和楼顶贴图,同时添加真实光照投影

👨‍⚕️ 主页: gis分享者 👨‍⚕️ 感谢各位大佬 点赞👍 收藏⭐ 留言📝 加关注✅! 👨‍⚕️ 收录于专栏:mapbox 从入门到精通 文章目录 一、🍀前言1.1 ☘️mapboxgl.Map 地图对象1.2 ☘️mapboxgl.Map style属性1.3 ☘️threebox extrusion挤出几何体1.3 ☘️…...

【蓝桥杯速成】| 2.逆向思维

题目一&#xff1a;青蛙跳台阶 题目描述 一只青蛙一次可以跳上1级台阶&#xff0c;也可以跳上2级台阶。 求该青蛙跳上一个 n 级的台阶总共有多少种跳法。 解题步骤 选用递归的方法解决该问题&#xff01; 使用递归只需要考虑清楚边界条件/终止条件&#xff0c;再写清楚单层…...

halcon机器人视觉(四)calibrate_hand_eye_stationary_3d_sensor

目录 一、准备数据和模型二、按照表面匹配的的结果进行手眼标定三、根据标定结果计算CalObjInCamPose一、准备数据和模型 1、读3D模型:read_object_model_3d 2、创建表面匹配模板:create_surface_model 3、创建一个HALCON校准数据模型:create_calib_data read_object_mode…...

python-leetcode-叶子相似的树

872. 叶子相似的树 - 力扣&#xff08;LeetCode&#xff09; 下面是一个完整的 Python 函数&#xff0c;接收两个二叉树的根节点 root1 和 root2&#xff0c;返回它们是否叶相似。 代码实现 class TreeNode:def __init__(self, val0, leftNone, rightNone):self.val valself…...

<03.13>八股文补充知识

import java.lang.reflect.*; public class Main {public static void main(String[] args) throws Exception {// 获取 Class 对象//1. 通过类字面量Class<?> clazz Person.class;//2 通过对象实例化String str "Hello";Class<?> clazz_str str.ge…...

GraphRAG 融合 RAG:双剑合璧,精度更上一层楼

检索增强生成 (Retrieval-Augmented Generation, RAG) 已成为构建知识密集型 NLP 应用的标准范式。RAG 通过结合大型语言模型 (LLM) 的生成能力和外部知识库的检索能力,显著提升了生成结果的质量。然而,在某些场景下,仅依靠传统的 RAG 或 GraphRAG 可能无法达到最佳效果。本…...

ffmpeg + opencv 打静态库编译到可执行文件中

下载ffmpeg ,我下载的为6.0 版本,解压后执行: ./configure --enable-static --disable-shared --pkg-config-flags=“–static” --extra-cflags=“-fPIC” --extra-cxxflags=“-fPIC” --prefix=/usr/local2.等待配置完成,执行 make && make install 进行编译安装…...

2025探索短剧行业新可能报告40+份汇总解读|附PDF下载

原文链接&#xff1a;https://tecdat.cn/?p41043 近年来&#xff0c;短剧以其紧凑的剧情、碎片化的观看体验&#xff0c;迅速吸引了大量用户。百度作为互联网巨头&#xff0c;在短剧领域积极布局。从早期建立行业专属模型冷启动&#xff0c;到如今构建完整的商业生态&#xf…...

前端面试:如何实现预览 PDF 文件?

在前端开发中&#xff0c;实现 PDF 文件的预览是一个常见需求&#xff0c;尤其是在应用程序中需要用户查看文档时。以下是几种常见的方法&#xff0c;可以用来实现在网页中预览 PDF 文件&#xff1a; 方法一&#xff1a;使用 <iframe> 标签 1. 基本实现 最简单的方式是…...

STM32 内置的通讯协议

数据是以帧为单位发的 USART和UART的区别就是有没有同步功能 同步是两端设备有时钟连接&#xff0c;异步是没时钟连接&#xff0c;靠约定号的频率&#xff08;波特率&#xff09;接收发送数据 RTS和CTS是用来给外界发送已“可接收”或“可发送”信号的&#xff0c;一般用不到…...

一个简单的PHP框架

原文地址&#xff1a;一个简单的PHP框架 更多内容请关注&#xff1a;智想天开 框架概述 一个基本的 PHP 框架通常包含以下几个部分&#xff1a; 前端控制器&#xff08;Front Controller&#xff09;&#xff1a;处理所有的 HTTP 请求&#xff0c;统一入口。 路由器&#xf…...

什么是SpringCloud?为何要选择SpringCloud?

什么是 Spring Cloud&#xff1f; Spring Cloud 是一套基于 Spring Boot 构建的 微服务架构解决方案&#xff0c;提供了一整套微服务开发所需的组件&#xff0c;如服务注册与发现、配置管理、负载均衡、熔断机制、网关等。它基于 Spring 生态系统&#xff0c;简化了分布式系统…...

信息安全访问控制、抗攻击技术、安全体系和评估(高软42)

系列文章目录 信息安全访问控制、抗攻击技术、安全体系和评估 文章目录 系列文章目录前言一、信息安全技术1.访问控制2.抗攻击技术 二、欺骗技术1.ARP欺骗2.DNS欺骗3.IP欺骗 三、抗攻击技术1.端口扫描2.强化TCP/IP堆栈 四、保证体系和评估1.保证体系2.安全风险管理 五、真题在…...

晋升系列4:学习方法

每一个成功的人&#xff0c;都是从底层开始打怪&#xff0c;不断的总结经验&#xff0c;一步一步打上来的。在这个过程中需要坚持、总结方法论。 对一件事情长久坚持的人其实比较少&#xff0c;在坚持的人中&#xff0c;不断的总结优化的更少&#xff0c;所以最终达到高级别的…...

脑电波控制设备:基于典型相关分析(CCA)的脑机接口频率精准解码方法

文章目录 前言一、CCA的用途二、频率求解思路三、输入数据结构四、判断方法五、matlab实践1.数据集获取及处理2.matlab代码3.运行及结果 六、参考文献 前言 在脑机接口(BCI)领域&#xff0c;有SSVEP方向&#xff0c;中文叫做稳态视觉诱发电位&#xff0c;当人观看闪烁的视觉刺激…...

Android Spinner总结

文章目录 Android Spinner总结概述简单使用自定义布局自定义Adapter添加分割线源码下载 Android Spinner总结 概述 在 Android 中&#xff0c;Spinner 是一个下拉选择框。 简单使用 xml布局&#xff1a; <Spinnerandroid:id"id/spinner1"android:layout_width&…...

element-ui layout 组件源码分享

layout 布局组件源码分享&#xff0c;主要从以下两个方面&#xff1a; 1、row 组件属性。 2、col 组件属性。 一、row 组件属性。 1.1 gutter 栅栏间隔&#xff0c;类型为 number&#xff0c;默认 0。 1.2 type 布局模式&#xff0c;可选 flex&#xff0c;现代浏览器下有效…...

OBJ文件生成PCD文件(python 实现)

代码实现 将 .obj 文件转换为 .pcd&#xff08;点云数据&#xff09; 代码文件。 import open3d as o3d# 加载 .obj 文件 mesh o3d.io.read_triangle_mesh("bunny.obj")# 检查是否成功加载 if not mesh.has_vertices():print("无法加载 .obj 文件&#xff0c…...

LinPEAS 使用最佳实践指南

在渗透测试和权限提升评估中&#xff0c;LinPEAS&#xff08;Linux Privilege Escalation Awesome Script&#xff09;是⼀个⽤来搜索类unix主机上可能的提权路径的⾃动化脚本。本文将介绍使用 LinPEAS 的最佳实践方案&#xff0c;并针对不同环境&#xff08;如无 curl 的情况&…...

c++介绍智能指针 十二(1)

普通指针&#xff1a;指向内存区域的地址变量。使用普通指针容易出现一些程序错误。 如果一个指针所指向的内存区域是动态分配的&#xff0c;那么这个指针变量离开了所在的作用域&#xff0c;这块内存也不会自动销毁。动态内存不进行释放就会导致内存泄露。如果一个指针指向已…...

Vue的scoped原理是什么?

scoped的工作原理 当在 <style> 标签上使用 scoped 属性时&#xff0c;Vue 会为当前组件的每个元素添加一个唯一的 data-v-xxxxxx 属性&#xff0c;并将样式规则中的选择器修改为包含该属性的形式。 编译阶段&#xff1a; 在编译 .vue 文件时&#xff0c;Vue 的编译器…...

大白话解释 React 中高阶组件(HOC)的概念和应用场景,并实现一个简单的 HOC。

高阶组件&#xff08;HOC&#xff09;的概念 在 React 里&#xff0c;高阶组件&#xff08;Higher-Order Component&#xff0c;简称 HOC&#xff09;就像是一个“超级工厂函数”。它本身是一个函数&#xff0c;而且这个函数接收一个组件作为参数&#xff0c;然后返回一个新的…...