我遇到了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方法返回我的char序列然后我放了一个.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) [...]
谢谢!
答案 0 :(得分:3)
检查您想先呼叫的字符串。
if(!newExpression.isEmpty() && newExpression.length() > expressionLength) {
String expressionNew = newExpression.subSequence(0, expressionLength).toString();
}
答案 1 :(得分:0)
在应用字符串运算符之前检查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");
}
答案 2 :(得分:0)
只是你想知道
我正在重置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");
}
}