zoukankan      html  css  js  c++  java
  • Why am I getting an Unreachable Statement error in Java?

     1 import java.util.*;
     2 import java.io.*;
     3 import java.nio.file.*;
     4 import java.lang.StringBuilder;
     5 
     6 class FilePrep {
     7     public static void main(String args[]) {
     8     }
     9     public String getStringFromBuffer() {
    10         try {
    11             Path file = Paths.get("testfile2.txt");
    12             FileInputStream fstream = new FileInputStream("testfile2.txt");
    13             BufferedReader br = new BufferedReader(new InputStreamReader(fstream));  
    14                 String inputLine = null;                    
    15             StringBuffer theText = new StringBuffer();  
    16 
    17             while((inputLine=br.readLine())!=null) {
    18                 theText.append(inputLine+" ");
    19             }
    20             return theText.toString();
    21             System.out.println(theText); // <-- line 21
    22         }
    23         catch (Exception e)
    24         {
    25             System.err.println("Error: " + e.getMessage());
    26             return null;
    27         }
    28     }
    29 }

    The full compiler output is:

    Main.java:21: error: unreachable statement
                System.out.println(theText);
                ^
    Main.java:28: error: missing return statement
        }
        ^
    2 errors

    解答

    You were right assuming that your problem is here:

    return theText.toString();
    System.out.println(theText);

    the return function will terminate your method, meaning no line of code past it will be executed. If you want your print to go through, you should move it above the return statement.

    reference: http://stackoverflow.com/questions/11488988/why-am-i-getting-an-unreachable-statement-error-in-java

  • 相关阅读:
    Linux下pip3安装问题
    客户信息维护jsp
    Java开发环境搭建
    软件开发一般步骤
    PM
    需求分析
    结对编程
    GUI
    spring boot 整合cfx,axis2创建webservice客户端
    webserver 返回json 如何去掉 <string xmlns="http://tempuri.org/">
  • 原文地址:https://www.cnblogs.com/hygeia/p/4621995.html
Copyright © 2011-2022 走看看