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
时间: 2024-10-06 15:40:24