0

I have a problem with Java and Android Studio; the following code was to be a backspace button:

else if(view == btnBackspace){
    int expressionLength = expression.length() - 2;
    String expressionNew = newExpression.subSequence(0, expressionLength); // new expression is the t

    editText.setText(expressionNew); // prints out text
}

I'm trying do a backspace button, I don't know if this is the better way of make this. So, subSequence method return's me that is a char sequence then I put a .toString() :

String expressionNew = newExpression.subSequence(0, expressionLength).toString();

But it doesn't work! The app compiles but when I press my backspace button the app stops and terminal points out the following exception:

FATAL EXCEPTION: main
java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=-2
at java.lang.String.startEndAndLength(String.java:583)
at java.lang.String.substring(String.java:1464) [...]

Thanks!

T D Nguyen
  • 7,054
  • 4
  • 51
  • 71
João Nobre
  • 51
  • 1
  • 10

3 Answers3

3

Check the String your want to call first.

if(!newExpression.isEmpty() && newExpression.length() > expressionLength) {
   String expressionNew = newExpression.subSequence(0, expressionLength).toString();
}
0

Check the length before applying the string operator. Try this:

int expressionLength = expression.length() - 2;
if(expressionLength>0)
{
     String expressionNew = newExpression.subSequence(0, expressionLength).toString(); // new expression is the t
     editText.setText(expressionNew); // prints out text
else {

     editText.setText("Empty expression string");
}
T D Nguyen
  • 7,054
  • 4
  • 51
  • 71
0

It is just if you want to know

I was reseting the var expression and the correct code for this is:

else if(view == btnBackspace){
    int expressionLength = expression.length() - 1;
    if(!expression.isEmpty() && expression.length() > expressionLength) {
        String expressionNew = expression.subSequence(0, expressionLength).toString();
        editText.setText(expressionNew);
    }
    else {
        editText.setText("Empty expression string");
    }
}
Termininja
  • 6,620
  • 12
  • 48
  • 49
João Nobre
  • 51
  • 1
  • 10