java - 在运算符(operator)签名之前跟踪数字

标签 java android calculator

对于计算器程序,我跟踪操作符符号之前的所有数字,并使用计数器将其数字限制为 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;

    }



  }
});

最佳答案

您可以尝试使用堆栈来保存计数器的历史记录。如果将堆栈限制为 2,则最终会得到当前数字的计数器和前一个数字的计数器。然后,如果您添加/删除标志,您需要做的就是管理堆栈。

关于java - 在运算符(operator)签名之前跟踪数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43536409/

相关文章:

calculator - Snake 风格游戏的简约方法

swift - 计算小数位数(Swift)

javascript - 日复一日,包括闰年

java - Spring只读事务提交数据到数据库

java - 控制 Graphics2D 对象的 DPI

java - Android 多次滑动 View

android - 滚动在交错的 Gridview 中产生间隙

android - 安卓版 clamav

java - 有效地将包含字母的字符串转换为 Int - Apache Spark

java - 从 JSONObject 中获取字符串