有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将字符串值解析为整数时出现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;
                    }
                }
            }
        });

共 (2) 个答案

  1. # 1 楼答案

    使用Integer.parseInt(String)时,字符串数据必须只有+-的数字或ASCII值,否则,它会抛出NumberFormatException

    public static int parseInt(String s) throws NumberFormatException

    Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.

    documentation

  2. # 2 楼答案

    看起来你没有得到一个int值。检查数据包含的内容,可能包含意外字符