【HarmonyOS——ArkTS语言】盘算器的实现【合集】

[复制链接]
发表于 2025-12-3 04:48:41 | 显示全部楼层 |阅读模式
目次
😋环境设置:华为HarmonyOS开发者
🎯学习小目的:
📺演示效果:
📖实行步调及方法:
1. 在index.ets文件中通过 @Extend(Button) 装饰器扩展Button 组件设置按钮样式函数myButton
2. 设置运算符摆列范例 Operator
3. 设置获取运算符优先级的函数 getOperatorPrecedence
4.设置盘算表达式效果的函数 calculateResult
5.设置主界面组件 Index
6.模仿机运行测试 
👋实行小结


😋环境设置:华为HarmonyOS开发者

🎯学习小目的:


  • 创建一个工程,在index.ets文件中举行编辑
  • 使用按钮组件计划盘算器的结构
  • 点击按钮后将盘算过程体现在Text组件中
  • 点击等号体现盘算效果
📺演示效果:

 
 

图1 预览器演示效果

📖实行步调及方法:

1. 在index.ets文件中通过 @Extend(Button) 装饰器扩展Button 组件设置按钮样式函数myButton

  1. @Extend(Button)
  2. function myButton() {
  3. .type(ButtonType.Normal)
  4. .width("270px")
  5. .height("270px")
  6. .backgroundColor(Color.Black)
  7. .border({ color: Color.White, style: BorderStyle.Solid, width: 2 })
  8. .fontSize(40)
  9. .fontColor(Color.White)
  10. .fontWeight(800)
  11. .borderRadius(0)
  12. }
复制代码
2. 设置运算符摆列范例 Operator

  1. enum Operator {
  2.   PLUS = '+',
  3.   MINUS = '-',
  4.   TIMES = '*',
  5.   DIVIDE = '/'
  6. }
复制代码
3. 设置获取运算符优先级的函数 getOperatorPrecedence

  1. function getOperatorPrecedence(operator: string): number {
  2.   switch (operator) {
  3.     case Operator.PLUS:
  4.     case Operator.MINUS:
  5.       return 1;
  6.     case Operator.TIMES:
  7.     case Operator.DIVIDE:
  8.       return 2;
  9.     default:
  10.       throw new Error("Invalid operator: " + operator);
  11.   }
  12. }
复制代码


4.设置盘算表达式效果的函数 calculateResult

  1. function calculateResult(expression: string): number {
  2.   // 去除表达式两端可能存在的空白字符
  3.   expression = expression.trim();
  4.   // 使用两个栈,一个用于存储操作数,一个用于存储运算符
  5.   let operandStack: number[] = [];
  6.   let operatorStack: string[] = [];
  7.   // 用于临时存储数字字符组成的字符串,以便转换为数字
  8.   let tempNumber = "";
  9.   for (let i = 0; i < expression.length; i++) {
  10.     let char = expression[i];
  11.     if (char >= '0' && char <= '9' || char === '.') {
  12.       // 如果是数字字符或小数点,累加到临时数字字符串中
  13.       tempNumber += char;
  14.     } else if (char === '+' || char === '-' || char === '*' || char === '/') {
  15.       // 如果是运算符
  16.       // 先将之前临时存储的数字转换为实际数字并压入操作数栈
  17.       if (tempNumber!== "") {
  18.         operandStack.push(Number(tempNumber));
  19.         tempNumber = "";
  20.       }
  21.       // 处理运算符栈,按照优先级进行运算
  22.       while (
  23.         operatorStack.length > 0 &&
  24.           getOperatorPrecedence(operatorStack[operatorStack.length - 1]) >= getOperatorPrecedence(char)
  25.       ) {
  26.         let operator = operatorStack.pop();
  27.         let operand2 = operandStack.pop();
  28.         +
  29.         let operand1 = operandStack.pop();
  30.         // 验证弹出的操作数是否有效
  31.         if (Operand1 === undefined || operand2 === undefined) {
  32.           throw new Error("Invalid operation: missing operand(s)");
  33.         }
  34.         if (operator === Operator.PLUS) {
  35.           operandStack.push(Operand1 + operand2);
  36.         } else if (operator === Operator.MINUS) {
  37.           operandStack.push(Operand1 - operand2);
  38.         } else if (operator === Operator.TIMES) {
  39.           operandStack.push(Operand1 * operand2);
  40.         } else if (operator === Operator.DIVIDE) {
  41.           operandStack.push(Operand1 / operand2);
  42.         }
  43.       }
  44.       // 将当前运算符压入运算符栈
  45.       operatorStack.push(char);
  46.     } else if (char === '(') {
  47.       // 如果是左括号,直接压入运算符栈
  48.       operatorStack.push(char);
  49.     } else if (char === ')') {
  50.       // 如果是右括号
  51.       // 先将之前临时存储的数字转换为实际数字并压入操作数栈
  52.       if (tempNumber!== "") {
  53.         operandStack.push(Number(tempNumber));
  54.         tempNumber = "";
  55.       }
  56.       // 处理运算符栈,直到遇到左括号
  57.       while (
  58.         operatorStack.length > 0 &&
  59.           operatorStack[operatorStack.length - 1]!== '(') {
  60.         let operator = operatorStack.pop();
  61.         let operand2 = operandStack.pop();
  62.         let operand1 = operandStack.pop();
  63.         // 验证弹出的操作数是否有效
  64.         if (Operand1 === undefined || operand2 === undefined) {
  65.           throw new Error("Invalid operation: missing operand(s)");
  66.         }
  67.         if (operator === Operator.PLUS) {
  68.           operandStack.push(Operand1 + operand2);
  69.         } else if (operator === Operator.MINUS) {
  70.           operandStack.push(Operand1 - operand2);
  71.         } else if (operator === Operator.TIMES) {
  72.           operandWordStack.push(Operand1 * operand2);
  73.         } else if (operator ==Operator.DIVIDE) {
  74.           operandStack.push(Operand1 / operand2);
  75.         }
  76.       }
  77.       // 弹出左括号
  78.       operatorStack.pop();
  79.     }
  80.   }
  81.   // 处理表达式末尾可能存在的数字
  82.   if (tempNumber!== "") {
  83.     operandStack.push(Number(tempNumber));
  84.   }
  85.   // 处理运算符栈中剩余的运算符
  86.   if (operatorStack.length > 0) {
  87.     let operator = operatorStack.pop();
  88.     let operand2 = operandStack.pop();
  89.     let operand1 = operandStack.pop();
  90.     // 验证弹出的操作数是否有效
  91.     if (Operand1 === undefined || operand2 === undefined) {
  92.       throw new Error("Invalid operation: missing operand(s)");
  93.     }
  94.     if (operator === Operator.PLUS) {
  95.         operandStack.push(Operand1 + operand2);
  96.     } else if (operator === Operator.MINUS) {
  97.         operandStack.push(Operand1 - operand2);
  98.     } else if (operator === Operator.TIMES) {
  99.         operandStack.push(Operand1 * operand2);
  100.     } else if (operator ==Operator.DIVIDE) {
  101.         operandStack.push(Operand1 / operand2);
  102.     }
  103.     }
  104.     // 返回最终的计算结果
  105.     return operandStack[0];
  106. }
复制代码
5.设置主界面组件 Index

  1. @Entry
  2. @Component
  3. struct Index {
  4.   @State result: string = ""
  5.   @State number: number = 0
  6.   build() {
  7.     Column() {
  8.       Row() {
  9.         Text(this.result).fontSize(50)
  10.       }
  11.       Row() {
  12.         Column() {
  13.           Button("7").onClick(() => {
  14.             this.result += "7"
  15.           }).myButton()
  16.         }
  17.         Column() {
  18.           Button("8").onClick(() => {
  19.             this.result += "8"
  20.           }).myButton()
  21.         }
  22.         Column() {
  23.           Button("9").onClick(() => {
  24.             this.result += "9"
  25.           }).myButton()
  26.         }
  27.         Column() {
  28.           Button("+").onClick(() => {
  29.             this.result += "+"
  30.           }).myButton()
  31.         }
  32.       }
  33.       Row() {
  34.         Column() {
  35.           Button("4").onClick(() => {
  36.             this.result += "4"
  37.           }).myButton()
  38.         }
  39.         Column() {
  40.           Button("5").onClick(() => {
  41.             this.result += "5"
  42.           }).myButton()
  43.         }
  44.         Column() {
  45.           Button("6").onClick(() => {
  46.             this.result += "6"
  47.           }).myButton()
  48.         }
  49.         Column() {
  50.           Button("-").onClick(() => {
  51.             this.result += "-"
  52.           }).myButton()
  53.         }
  54.       }
  55.       Row() {
  56.         Column() {
  57.           Button("1").onClick(() => {
  58.             this.result += "1"
  59.           }).myButton()
  60.         }
  61.         Column() {
  62.           Button("2").onClick(() => {
  63.             thisresult += "2"
  64.           }).myButton()
  65.         }
  66.         Column() {
  67.           Button("3").onClick(() => {
  68.             this.result += "3"
  69.           }).myButton()
  70.         }
  71.         Column() {
  72.           Button("*").onClick(() => {
  73.             this.result += "*"
  74.           }).myButton()
  75.         }
  76.       }
  77.       Row() {
  78.         Column() {
  79.           Button("0").onClick(() => {
  80.             this.result += "0"
  81.           }).myButton()
  82.         }
  83.         Column() {
  84.           Button(".").onClick(() => {
  85.             this.result += "."
  86.           }).myButton()
  87.         }
  88.         Column() {
  89.           Button("=").onClick(() => {
  90.             try {
  91.               this.result = calculateResult(this.result).toString();
  92.             } catch (e) {
  93.               this.result = "Error: " + e.message;
  94.             }
  95.           }).myButton()
  96.         }
  97.         Column() {
  98.           Button("/").onClick(() => {
  99.             this.result += "/"
  100.           }).myButton()
  101.         }
  102.       }
  103.       Row() {
  104.         Column() {
  105.           Button("C").onClick(() => {
  106.             this.result = "";
  107.             this.number = 0;
  108.           }).myButton()
  109.         }
  110.       }
  111.     }
  112.   }
  113. }
复制代码
6.模仿机运行测试   
 
 


👋实行小结

        本次盘算器应用开发实行告急围绕 index.ets 文件睁开。使用按钮组件顺遂完成结构计划,数字、运算符及功能按钮分列有序,操纵逻辑清晰直观。点击变乱处置惩罚精准,盘算过程能及时且无误地出现在 Text 组件,点击等号后盘算函数高效剖析表达式并给出正确效果,告竣核心功能要求。然而,实行中也发现一些待改进之处,比方错误提示不敷过细,难以助力用户快速定位输入错误;界面雅观性欠佳,颜色与样式缺乏风雅感;相应式计划不敷,在差别屏幕规格下适配性差。总体而言,本次实行已乐成构建起根本功能框架,后续将针对上述题目深入探究优化方案,不绝打磨细节,在美满盘算器功能与提升用户体验的蹊径上连续精进,进而提升自身编程与应用开发的综合本领程度。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表