对于计算器程序,我在操作员签名之前跟踪所有数字,并使用计数器将其数字限制为12,当选择操作员符号时,它会将计数器重置为零。这样做的问题是,如果我删除符号并继续编辑之前的数字,则计数不再生效,因为它在操作员签名后已重置为0。还有另一种方法可以解决这个问题吗?
提前致谢!
private int numericCounter;
private boolean operatorAssigned;
private int cap = 12;
//if the number of digits is not 12, allow input
if (!(numericCounter >= cap)) {
textView.append(button.getText());
}
//if an operator "+" "-"...
//is rececived set numeric counter to 0
if (operatorAssigned) {
numericCounter = 0;
}
if (numericCounter == 0) {
operatorAssigned = false;
}
//Notification
if (numericCounter >= cap) {
Context context = getApplicationContext();
CharSequence text = "Maximum number of digits(12) reached";
int duration = Toast.LENGTH_SHORT;
//... show one Toast
if (mToast != null) mToast.cancel();
mToast = Toast.makeText(context, text, duration);
mToast.show();
//show another Toast
if (mToast != null) mToast.cancel();
mToast = Toast.makeText(context, text, duration);
mToast.show();
}
//if maximum number of digits allowed
//not equal to 12
//increment numeric counter by 1
if (!(numericCounter >= cap)) {
numericCounter++;
}
//Handles the delete button
findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = textView.getText().toString();
if ((!text.isEmpty() && resultComputed == false)) {
String lastText = text.substring(0, text.length() - 1);
textView.setText(lastText);
lastNumeric = true;
//Checks if deleted text is a digit or an operator
if (lastText != "." || lastText != "+" || lastText != "-" || lastText != "/" || lastText != "/") {
numericCounter--;
}
} else if ((!text.isEmpty() && resultComputed == true)) {
textView.setText(txt);
resultComputed = false;
}
}
});
答案 0 :(得分:0)
您可以尝试使用堆栈来保留计数器的历史记录。如果将堆栈限制为2,则最终会得到当前数字的计数器和前一个数字的计数器。然后,您需要做的就是在添加/删除标志时管理堆栈。
答案 1 :(得分:0)
只需创建备份变量即可。
之类的东西private int backUp = 0;
然后在if(operatorAssigned)
函数中,
这样做:
backUp = numericCounter;
numbericCounter = 0;
这样,如果您检查是否删除了运算符,只需将backUp
的值再次分配给numericCounter
。
这只是一个非常基本的想法。