为什么 StringIndexOutOfBoundsException 与 subSequence?

Why StringIndexOutOfBoundsException with subSequence?

我对 Java 和 Android Studio 有疑问;以下代码是一个退格键:

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
}

我正在尝试做一个退格按钮,我不知道这是否是更好的制作方法。所以,subSequence 方法 return 是一个字符序列,然后我放了一个 .toString() :

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

但是不行!该应用程序可以编译,但是当我按下退格键时,该应用程序停止并且终端指出以下异常:

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) [...]

谢谢!

在应用字符串运算符之前检查length。试试这个:

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");
}

先勾选你要调用的String。

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

只要你想知道

我正在重置 var 表达式,正确的代码是:

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");
    }
}