鸿蒙手机计算器开发练习 原创

蛟龙腾飞
发布于 2021-6-1 14:50
浏览
2收藏

一、具体功能实现

 

运行项目后点击数字和运算符,然后点击运算得到结果

 

如果直接点击计算会给出提示

  鸿蒙手机计算器开发练习-鸿蒙开发者社区

 

如何输入不符合要求的算式会给出提示

例如

第一项是运算符或连续输入运算符或最后一项是运算符会提示

鸿蒙手机计算器开发练习-鸿蒙开发者社区  鸿蒙手机计算器开发练习-鸿蒙开发者社区

  

  鸿蒙手机计算器开发练习-鸿蒙开发者社区

0做除数会提示

  鸿蒙手机计算器开发练习-鸿蒙开发者社区

 

 

正常测试

  鸿蒙手机计算器开发练习-鸿蒙开发者社区

结果

  

鸿蒙手机计算器开发练习-鸿蒙开发者社区

 

 

二、部分核心代码展示

// 循环数字数组
for (int i = 0; i < numButtons.length; i++) {
    int finalI = i;
    numButtons[i].setClickedListener((component) -> text.setText(text.getText() + numButtons[finalI].getText()));
}
// 循环操作符数组
for (int i = 0; i < operatorButtons.length; i++) {
    int finalI = i;
    operatorButtons[i].setClickedListener((component) -> {
        if(text.getText().equals("")) {
            new ToastDialog(getContext()).setAutoClosable(true).setSize(800,100).setDuration(2000).setText("请先输入数字").show();
            return;
        } else if(operators.contains(text.getText().substring(text.length()-1))) {
            new ToastDialog(getContext()).setAutoClosable(true).setSize(800,100).setDuration(2000).setText("请不要连续输入运算符").show();
            return;
        }
        text.setText(text.getText() + operatorButtons[finalI].getText());
    }
);
}


// 设置退格键的点击事件
backspace.setClickedListener((component) -> {
    if (text.getText()!=null && !text.getText().trim().equals(""))
        {
            text.setText(text.getText().substring(0,text.length()-1));
        }
});

// 计算结果
button.setClickedListener((component) -> {
    String target = text.getText();
    if (operators.contains(text.getText().substring(text.length()-1))) {
        new ToastDialog(getContext()).setAutoClosable(true).setSize(800,100).setDuration(2000).setText("请不要以运算符结尾").show();
        return;
    } else if (target.contains("错误")) {
        new ToastDialog(getContext()).setAutoClosable(true).setSize(800,100).setDuration(2000).setText("请").show();
        return;
    }
    try {
        if ((Calculate.cacl(Calculate.analyze(target)) + "").equals("Infinity")) {
            new ToastDialog(getContext()).setAutoClosable(true).setSize(800, 100).setDuration(2000).setText("0不能作为除数").show();
        } else {
            text.setText(Calculate.cacl(Calculate.analyze(target))+ "");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
});

 

三、完整代码下载地址

https://gitee.com/jltfcloudcn/jump_to/tree/master/JLTFCalculator

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
标签
鸿蒙手机计算器开发练习.docx 1.73M 182次下载
2
收藏 2
回复
举报
1条回复
按时间正序
/
按时间倒序
鸿蒙时代
鸿蒙时代

公司认证账户第一篇文章发布。

回复
2021-6-1 16:24:59
回复
    相关推荐