首页 > 编程语言 > 详细

Why am I getting an Unreachable Statement error in Java?

时间:2015-07-05 13:43:57      阅读:234      评论:0      收藏:0      [点我收藏+]
 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

Why am I getting an Unreachable Statement error in Java?

原文:http://www.cnblogs.com/hygeia/p/4621995.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!