简体   繁体   English

计算器android中的小数点

[英]Decimal points in calculator android

I am creating a calculator app in android.我正在 android 中创建一个计算器应用程序。 The issue is how can I check for existence of two decimals in a single numeric value .问题是如何检查单个数值中是否存在两位小数。 Currently my calculator allows inputs such as 1.2.3 which is illegal .目前我的计算器允许输入如1.2.3这是非法的。 It must allow a decimal if an operator has been used.如果使用了运算符,则必须允许使用小数。 Eg 1.1+2.2 is legal but 1.1.1+2.2 isn't.例如1.1+2.2是合法的,但1.1.1+2.2不是。 Here is my code for decimal handling:这是我的十进制处理代码:

public class TrialCalculator extends AppCompatActivity implements Button.OnClickListener {
    Button btn1, btn2, btnBack, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnPlus, btnMinus, btnMul, btnDiv, btnEquals, btnClear, btnDecimal, btnPercent;
    EditText calcResult;
    double number = 0;
    private char opcode = '1';

    private void handleDecimal() {
        if (opcode == 0) clear();
        if (calcResult.getText() == null) {
            calcResult.setText("0.");
            calcResult.setSelection(2);
        } else {
            String txt = calcResult.getText().toString();
            if (txt.lastIndexOf(".")<txt.length()-1) {
                calcResult.append(".");
            }
        }
    }
}

I am calling the buttonDot from onClick Method.我从onClick方法调用buttonDot

One solution is to have a flag which keeps track of the decimal:一种解决方案是拥有一个跟踪小数的标志:

class MyCalculator {
    private hasDecimal = false;

    // ...
}

Set this flag to true the first time that the user types a decimal.用户第一次键入小数时,将此标志设置为true Then check the flag to see if a decimal has been previously typed.然后检查标志以查看之前是否输入了小数。

Of course, this only works if you are responding to each key press directly rather than getting the entire input from a EditText after the user has typed the entire number.当然,这仅适用于直接响应每个按键而不是在用户输入整个数字后从EditText获取整个输入的情况。

You can use regex with matches function您可以将正则表达式与matches功能一起使用

\\\\d* mean match zero or more digits \\\\d*表示匹配零个或多个数字

(\\\\.\\\\d+)? match a .匹配一个. followed by one or more digits , ?后跟一位或多位数字 , ? mean matches between zero or one times of given group给定组的零次或一次之间的平均匹配

Regex Demo : note with matches function in java, we don't need ^ start and $ ending anchors正则表达式演示:注意 java 中的matches功能,我们不需要^开始和$结束锚点

Code代码

if (txt.matches("\\d*(\\.\\d+)?")) {
   // number has one decimal
  }
else{
   // number has more than one decimal
}

Note: if you don't want to allow values like .5 then use \\\\d+ instead of \\\\d* as注意:如果你不想允许像.5这样的值,那么使用\\\\d+而不是\\\\d*作为

\\\\d+(\\\\.\\\\d+)?

As suggested by @Code-Apprentice , if you want to accept values like 4343. etc you can use正如@Code-Apprentice 所建议的,如果你想接受像4343.这样的值,你可以使用

\\d*(\\.\\d*)?

Using text watcher使用文本观察器

calcResult.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void afterTextChanged(Editable s) {
        boolean flag = s.toString().matches("\\d*(\\.\\d*)?");
        if(!flag){
            // calcResult.setError...
            // you display a toast 
        }             
    }
});

Update : To match multiple values with operators , you can use更新:要将多个值与运算符匹配,您可以使用

(\\d*(\\.\\d*)?([+\\-*%\\]|$))*

RegEx demo正则表达式演示

Test Cases测试用例

String pat="(\\d*(\\.\\d*)?([+\\-*%\\]|$))*";
System.out.println("4.5-3.3+3.4".matches(pat));
System.out.println(".5".matches(pat));
System.out.println("4".matches(pat));
System.out.println("4.5.5-4.4".matches(pat));
System.out.println("4.44.5+4.4.4".matches(pat));
System.out.println("4.".matches(pat));

Output :输出 :

true
true
true
false
false
true

lastIndexOf returns -1 if the character is not found in the string.如果在字符串中找不到该字符,则lastIndexOf返回 -1。 So your condition txt.lastIndexOf(".")<txt.length()-1 is always true .所以你的条件txt.lastIndexOf(".")<txt.length()-1总是true You could change it to你可以把它改成

txt.lastIndexOf(".") == -1

To check for existence of two decimals in a single no then split the string by decimal.要检查单个 no 中是否存在两个小数,然后按十进制拆分字符串。

for eg,例如,

String txt = calcResult.getText().toString();
String[] decimals = txt.split("\\.");
if(decimals.length > 2) {
// txt contains more than 1 decimal.
// Your logic ..
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM