在解码字符串模式 a-695b-36c158d-666e-1326f144 时,出现字符串索引越界异常。我想提取 a 和 b、b 和 c、c 和 d 之间的值。
此代码有时可以正确打印值,但有时会失败。我不明白为什么有时会出现这种异常。
下面是我的代码:
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[128];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
int buflen=buffer.length;
String str = new String(buffer, "UTF-8"); // prints character
Log.d("Data Transmitted", str);
int spaceIndex = str.indexOf(" ");
if (spaceIndex != -1)
{
str = str.substring(0, spaceIndex);
}
Log.d("Data Edited", str);
boolean v1=str.contains("a");
boolean v2=str.contains("b");
boolean v3=str.contains("c");
boolean v4=str.contains("d");
if(v1==true && v2==true && v3==true && v4==true){
mEmulatorView.write(buffer, bytes);
String op1=str.substring(str.indexOf("a")+1, str.indexOf("b"));
Log.d("output", op1);
String op2=str.substring(str.indexOf("b")+1, str.indexOf("c"));
Log.d("output", op2);
String op3=str.substring(str.indexOf("c")+1, str.indexOf("d"));
Log.d("output", op3);
}
else{
mEmulatorView.write(buffer, bytes);
}
// Send the obtained bytes to the UI Activity
//mHandler.obtainMessage(BlueTerm.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
我总是以这种形式获取数据: 12-12 12:43:54.681:D/数据传输(23778):a-695b-36c158d-666e-1326f144
12-12 12:43:54.681:D/数据传输(23778):a-684b-75c35d-659e-838f119
12-12 12:43:54.681:D/数据传输(23778):a-674b-353c238d-658e-556f148
异常:
> E/AndroidRuntime(23778): FATAL EXCEPTION: Thread-2313
> E/AndroidRuntime(23778): Process: es.pymasde.blueterm, PID: 23778
> E/AndroidRuntime(23778):
> java.lang.StringIndexOutOfBoundsException:length=128; regionStart=29;
> regionLength=-26 E/AndroidRuntime(23778): at
> java.lang.String.startEndAndLength(String.java:588)
> E/AndroidRuntime(23778): at
> java.lang.String.substring(String.java:1475)
最佳答案
如果 a
、b
、c
、d
的索引不是,您将得到该异常按照预期的顺序。
例如,如果 a
的第一个索引位于 b
的第一个索引之后,则表达式 str.substring(str.indexOf("a")+1, str.indexOf("b"))
将抛出此异常,如 Javadoc for the substring
method 中所述。 , promise ...
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex..
关于java - 字符串异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27438883/