[英]Decimal points in calculator android
我正在 android 中創建一個計算器應用程序。 問題是如何檢查單個數值中是否存在兩位小數。 目前我的計算器允許輸入如1.2.3
這是非法的。 如果使用了運算符,則必須允許使用小數。 例如1.1+2.2
是合法的,但1.1.1+2.2
不是。 這是我的十進制處理代碼:
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(".");
}
}
}
}
我從onClick
方法調用buttonDot
。
一種解決方案是擁有一個跟蹤小數的標志:
class MyCalculator {
private hasDecimal = false;
// ...
}
用戶第一次鍵入小數時,將此標志設置為true
。 然后檢查標志以查看之前是否輸入了小數。
當然,這僅適用於直接響應每個按鍵而不是在用戶輸入整個數字后從EditText
獲取整個輸入的情況。
您可以將正則表達式與matches
功能一起使用
\\\\d*
表示匹配零個或多個數字
(\\\\.\\\\d+)?
匹配一個.
后跟一位或多位數字 , ?
給定組的零次或一次之間的平均匹配
正則表達式演示:注意 java 中的matches
功能,我們不需要^
開始和$
結束錨點
代碼
if (txt.matches("\\d*(\\.\\d+)?")) {
// number has one decimal
}
else{
// number has more than one decimal
}
注意:如果你不想允許像.5
這樣的值,那么使用\\\\d+
而不是\\\\d*
作為
\\\\d+(\\\\.\\\\d+)?
正如@Code-Apprentice 所建議的,如果你想接受像4343.
這樣的值,你可以使用
\\d*(\\.\\d*)?
使用文本觀察器
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
}
}
});
更新:要將多個值與運算符匹配,您可以使用
(\\d*(\\.\\d*)?([+\\-*%\\]|$))*
測試用例
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));
輸出 :
true
true
true
false
false
true
如果在字符串中找不到該字符,則lastIndexOf
返回 -1。 所以你的條件txt.lastIndexOf(".")<txt.length()-1
總是true
。 你可以把它改成
txt.lastIndexOf(".") == -1
要檢查單個 no 中是否存在兩個小數,然后按十進制拆分字符串。
例如,
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.