将字符串值解析为整数

我从蓝牙获取数据,该数据是字符串类型,并且我试图在android studio中将此值解析为整数,并且出现此错误“ java.lang.NumberFormatException:Int 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,encodedBytes,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;
                    }
                }
            }
        });
cctvmtv1989 回答:将字符串值解析为整数

我不知道您从数据中获得什么价值。但是我可以说,当您尝试将字符串转换为无效的Int时,会出现NumberFormatException。 示例:

String data =“ ABC”; 将其转换为Integer时将引发异常。因为“ ABC”不是整数。

因此,您能否检查一下数据中到底获得了什么价值? 另外,添加一个try-catch块

try{
    int i = Integer.parseInt(input);
} catch(NumberFormatException ex){ // handle your exception
    ...
}
,

使用Integer.parseInt(String)时,字符串数据只能包含数字或ASCII值+-,否则将抛出NumberFormatException

  

公共静态int parseInt(String s)                       引发NumberFormatException

     

将字符串参数解析为带符号的十进制整数。那些角色   字符串中的所有字符必须全部为十进制数字,但第一个除外   字符可以是ASCII减号'-'('\ u002D'),以表示   负值或ASCII加号'+'('\ u002B')表示   正值。

     

documentation

,

似乎您没有接收到int值。检查其中包含哪些数据,也许其中包含一些意外字符。

本文链接:https://www.f2er.com/3158244.html

大家都在问