Java 如何将接收到的数字一分为二

Java 如何将接收到的数字一分为二,java,android,arduino,Java,Android,Arduino,亲爱的stackoverflow社区大家好, 我正在做一个项目,它接收来自arduino模块的信息,并将其显示为图表。 问题是我有5个元素(温度、湿度等),我的代码一次只能接收一个数字(例如:2838752458),正如您在示例中看到的,数字有10个数字,来自arduino,我想将它们两个两个分开,以便每两个都对应一个元素。 您可能会问,为什么我不设置一个处理程序,这样我可以在一个单独的时间接收每两个数字,但我已经尝试过了,它会给我一个关闭的应用程序错误,因为我的代码一次只能接收一个数字 p

亲爱的stackoverflow社区大家好, 我正在做一个项目,它接收来自arduino模块的信息,并将其显示为图表。 问题是我有5个元素(温度、湿度等),我的代码一次只能接收一个数字(例如:2838752458),正如您在示例中看到的,数字有10个数字,来自arduino,我想将它们两个两个分开,以便每两个都对应一个元素。 您可能会问,为什么我不设置一个处理程序,这样我可以在一个单独的时间接收每两个数字,但我已经尝试过了,它会给我一个关闭的应用程序错误,因为我的代码一次只能接收一个数字

  public class Analysies extends AppCompatActivity {                
        Handler h;        
        String tekrar = "";
        String dama = "";
        String qaza = "";
        String faaliat = "";
        String rotobat = "";
        private OutputStream outStream = null;
        private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

        private static String address = "00:21:13:00:02:5B";

        final int RECIEVE_MESSAGE = 1;        // Status  for Handler
        private BluetoothAdapter btAdapter = null;
        private BluetoothSocket btSocket = null;
        private StringBuilder sb = new StringBuilder();

        private Analysies.ConnectedThread mConnectedThread;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_analysies);

            gifImageView = (GifImageView) findViewById(R.id.gifBro);
            txt1 = (GifImageView) findViewById(R.id.afterAutotxt);


            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {        
                    txt1.animate().alpha(1f).setDuration(2000);
                }
            }, 1000);        
            h = new Handler() {
                public void handleMessage(android.os.Message msg) {
                    switch (msg.what) {
                        case RECIEVE_MESSAGE:                                                   
                            // if receive massage
                            byte[] readBuf = (byte[]) msg.obj;
                            String strIncom = new 
                            String(readBuf, 0, msg.arg1);                 
                            // create string from bytes array
                            sb.append(strIncom);                                                
                            // append string
                            int endOfLineIndex = sb.indexOf("\r\n");                            
                            // determine the end-of-line
                            if (endOfLineIndex > 0) {                                            
                            // if end-of-line,
                                String sbprint = sb.substring(0, endOfLineIndex);                // extract string
                                sb.delete(0, sb.length());
                                sbprint.getBytes().toString();


////////////////////////////// HERE IS WHERE I CAN RECEIVE INFORMATION FROM ARDUINO ///////////////////////////////

                            }
                            //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
    //                        Toast.makeText(CommunicationAuto.this, "String:" + sb.toString() , Toast.LENGTH_LONG).show();
                            break;
                    }
                }

                ;
            };

            btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
            checkBTState();
       }

        private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
            if(Build.VERSION.SDK_INT >= 10){
                try {
                    final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
                    return (BluetoothSocket) m.invoke(device, MY_UUID);
                } catch (Exception e) {
    //                Toast.makeText(getApplicationContext(), "Could not Insecure", Toast.LENGTH_SHORT).show();
                }
            }
            return  device.createRfcommSocketToServiceRecord(MY_UUID);
        }

        @Override
        public void onResume() {
            super.onResume();

            // Set up a pointer to the remote node using it's address.
            BluetoothDevice device = btAdapter.getRemoteDevice(address);

            // Two things are needed to make a connection:
            //   A MAC address, which we got above.
            //   A Service ID or UUID.  In this case we are using the
            //     UUID for SPP.

            try {
                btSocket = createBluetoothSocket(device);
            } catch (IOException e) {
    //            Toast.makeText(getApplicationContext(), "Socket failed", Toast.LENGTH_SHORT).show();
            }

            // Discovery is resource intensive.  Make sure it isn't going on
            // when you attempt to connect and pass your message.
            btAdapter.cancelDiscovery();

            // Establish the connection.  This will block until it connects.
    //        Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
            try {
                btSocket.connect();
    //            Toast.makeText(getApplicationContext(), "Connecting ok!", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                try {
                    btSocket.close();
                } catch (IOException e2) {
    //                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
                }
            }

            // Create a data stream so we can talk to server.


            mConnectedThread = new Analysies.ConnectedThread(btSocket);
            mConnectedThread.start();
        }

        @Override
        public void onPause() {
            super.onPause();        
            try     {
                btSocket.close();
            } catch (IOException e2) {
    //            errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
            }
        }

        private void checkBTState() {
            // Check for Bluetooth support and then check to make sure it is turned on
            // Emulator doesn't support Bluetooth and will return null
            if(btAdapter==null) {


                Toast.makeText(getApplicationContext(), " Bluetooth is not supported. ", Toast.LENGTH_SHORT).show();

            } else {
                if (btAdapter.isEnabled()) {

                } else {

                   Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, 1);


                }
            }
        }

        private void errorExit(String title, String message){
            Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
            finish();
        }

        private class ConnectedThread extends Thread {
            private final InputStream mmInStream;
            private final OutputStream mmOutStream;

            public ConnectedThread(BluetoothSocket socket) {
                InputStream tmpIn = null;
                OutputStream tmpOut = null;

                // Get the input and output streams, using temp objects because
                // member streams are final
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) { }

                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }

            public void run() {
                byte[] buffer = new byte[256];  // buffer store for the stream
                int bytes; // bytes returned from read()

                // Keep listening to the InputStream until an exception occurs
                while (true) {
                    try {
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                        h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
                    } catch (IOException e) {
                        break;
                    }
                }
            }

            /* Call this from the main activity to send data to the remote device */
            public void write(String message) {


                byte[] msgBuffer = message.getBytes();
                try {
                    mmOutStream.write(msgBuffer);
                } catch (IOException e) {


                }
            }
        }
    }
问题:如何将10位数字2除以2,并将其添加到分隔的整数中,以便将其传递给图表活动?请给我一个“1234567890”这个数字的例子

是到目前为止我创建的图表的输出


谢谢大家!

首先确保您的位数(例如:1234567890)始终可以被2整除。好吧,那我就给你点建议

首先,将
数字
转换为
字符串
,并在第2步中运行
for循环
,然后只需将第i个(i+1)个位置的字符附加到使用循环生成的每个字符串中,形成一个数组。最后,您可以从数组列表中读取项并将值发送到图表,只需将
字符串
解析为
int
值即可。下面是我使用Kotlin编写的示例代码(但如果需要,我可以将其转换为Java代码)。如果您面临任何问题,请随时发表评论

fun main() {
    val digits = 1234567890
    val arr = arrayListOf<String>()

    for (i in 0 until digits.toString().length step 2) {
        val sub = "${digits.toString()[i]}${digits.toString()[i+1]}"
        arr.add(sub)
    }
    println(arr)
}
fun main(){
val数字=1234567890
val arr=arrayListOf()
for(0中的i,直到数字.toString().length第2步){
val sub=“${digits.toString()[i]}${digits.toString()[i+1]}”
附件(附件)
}
println(arr)
}

快乐编码

这似乎是你想要的:

import java.util.regex.*;

public class HelloWorld{


    public static void main(String []args){

       String s = "1234567890";

       String pattern = "(\\d\\d)";
       Pattern p = Pattern.compile(pattern);
       Matcher m = p.matcher(s);
       while (m.find()) {
           System.out.println(m.group(0));
       } 

    }
}
和输出:

12
34
56
78
90