将字符串值解析为整数时出现java错误
我从蓝牙获取数据,这是字符串类型的数据,我试图在安卓 studio中将这个值解析为整数,我得到了一个错误“java.lang.NumberFormatException:Invalid int:”那么我该怎么解决它呢。 这是我的java代码:
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while(!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = inputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
inputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
if(Integer.parseInt(data)<10) {//Here the error
addNotification();
}
System.out.println(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
# 1 楼答案
使用
Integer.parseInt(String)
时,字符串数据必须只有+
和-
的数字或ASCII值,否则,它会抛出NumberFormatException
# 2 楼答案
看起来你没有得到一个int值。检查数据包含的内容,可能包含意外字符