3

I am creating a calculator app for a class and I have everything working except the "BackSpace" Button. The only information that I can find on manipulating the TextView is using the SetText method to reset the TextView to either null or just an empty string. What I need to do though is remove the last number entered into the calculator ex: if the number 12 is entered in and the backspace button is pressed it will delete the 2 but leave the 1. I decided to only include my "onClick" method as its the only method relevant to this question all the calculations are done in another method. Thanks!

 public void onClick(View v) {

        // display is assumed to be the TextView used for the Calculator display
        String currDisplayValue = display.getText().toString();

        Button b = (Button)v;  // We assume only buttons have onClickListeners for this App
        String label = b.getText().toString();  // read the label on the button clicked

        switch (v.getId())
        {
            case R.id.clear:
                calc.clear();
               display.setText("");
                //v.clear();
                break;
            case R.id.plus:
            case R.id.minus:
            case R.id.mult:
            case R.id.div:
                String operator = label;
                display.setText("");
                calc.update(operator, currDisplayValue);

                break;
            case R.id.equals:
              display.setText(calc.equalsCalculation(currDisplayValue));
                break;

            case R.id.backSpace:
                // Do whatever you need to do when the back space button is pressed
                //Removes the right most character ex: if you had the number 12 and pressed this button
                //it would remove the 2. Must take the existing string, remove the last character and
                //pass the new string into the display.

                display.setText(currDisplayValue);
                break;
            default:
                // If the button isn't one of the above, it must be a digit
                String digit = label;// This is the digit pressed
                display.append(digit);
                break;
        }
    }
auth private
  • 1,318
  • 1
  • 9
  • 22
Dave
  • 61
  • 1
  • 1
  • 4

1 Answers1

9

Use Substring

It will allow you to replace / remove characters by index (in your case it will be the last index of the string)

NumberEntered = NumberEntered.substring(0, NumberEntered.length() - 1);

If you have a number entered 1829384

Length is 7, index will start at 0

When substringed it will be from 0 to (7-1) thus new string will be 182938

Fred L
  • 242
  • 1
  • 4