Search code examples
javaandroidcalculatorbackspace

wcalculator delete button alternative to enteredInput.length() - 1);


Hello everyone i am new with Java and i am bulding a calculator project i use this for DEL button (backspace)

if(data.equals("DEL")){
                String enteredInput = outputResult.getText().toString();
                if(enteredInput.length() > 0){
                    enteredInput = enteredInput.substring(0, enteredInput.length() - 1);
                    currentDisplayedInput = enteredInput;
                    inputToBeParsed = enteredInput;
                    outputResult.setText(currentDisplayedInput);
                }

it works fine to delete the last digit, but i use functions like sine, ...etc it is on the textview as "sine(" , when Del button is clicked it deletes the last character which in this case "(" ... i need it to delete the input not the last character (The whole sine)


Solution

  • Okay...I have not done Java for half a year. So please forgive me if my answer seems unclear.

    Alright, you need to delete the last entry in your calculator made by the user...

    I suggest that you use a List of type String to do this.

    Every time the user clicks a button of your calculator add the entry to the end of the List e.g if the user clicks one the plus then sine, the elements in the list should be as follows:

    {"1", "+", "sin("}
    

    Now, when the user clicks the Delete button...your program does record that the delete button was clicked but rather it removes the last element of the list such that the elements of the above list will be as follows:

    {"1", "+"}
    

    Displaying the Mathematical expression in the text field should be fairly simple, but do it efficiently. Some programmers might display all the elements of the list over and over again as the list is updated. You could display the mathematical expressions another way without iterating through the List to do this. Hint: Use String methods.

    Hope this helps.

    I am keen to see answers for this question that don't use Lists or arrays.