简体   繁体   中英

Giving “unreachable code” error

Good day. Can somebody help me. I can't seem to find a way to fix this problem. I don't know why i am getting "unreachable code" error when i close the InputStream and the socket..

Thank you for the help.

 public void run() {
          try {
           socket = new Socket(dstAddress, dstPort);

           ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
           byte[] buffer = new byte[1024];

           int bytesRead;
           InputStream inputStream;

           while (true) {
                inputStream = socket.getInputStream();

                while ((bytesRead = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    response += byteArrayOutputStream.toString("UTF-8");
                }
                textResponse.setText(response);
                if(response == "Server: You are connected to Android Server"){
                    Log.v("ok","ppp");
                }
                if(response == "OK"){
                    Log.v("ok","ooo");
                }
           }

           inputStream.close();    --------unreachable code
           socket.close();         --------unreachable code

          } catch (UnknownHostException e) {
           e.printStackTrace();
           response = "UnknownHostException: " + e.toString();
          } catch (IOException e) {
           e.printStackTrace();
           response = "IOException: " + e.toString();
          }
  }

while (true) {} is an endless loop and you're not breaking from it, hence the two close() statements being unreachable.

When your condition is met inside the while loop, you can use break; statement to continue executing the code below the while 's scope.

t while (condition) { inputStream = socket.getInputStream();

                while ((bytesRead = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    response += byteArrayOutputStream.toString("UTF-8");
                }
                textResponse.setText(response);
                if(response == "Server: You are connected to Android Server"){
                    Log.v("ok","ppp");
                }
                if(response == "OK"){
                    Log.v("ok","ooo");
                }
           }

your while (true) is looping all the time. You need to break the while to go to next line. In your case it wont go to next line since while not ending. You may change while to if , it its not looping statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM