我试图返回方法的值但是循环抛出错误,因为返回必须在方法体中而不是在循环中。我正在使用system.out.println,它是有效的,但我想使用返回。
package AnimeAid;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadFile {
public void getFileInformation() throws IOException {
try{
String file;
file = "tra.srt";
Charset charset = Charset.defaultCharset();
Path path = Paths.get(file);
BufferedReader reader = Files.newBufferedReader(path, charset);
System.out.printf("Lines from %s:%n",file);
String line;
while((line = reader.readLine()) != null) {
if (line.indexOf(':') != -1 && line.indexOf(',') != -1 && line.indexOf('0') != -1) {
System.out.println(line.substring(0, 12));
}
}
}catch(FileNotFoundException ex){
System.err.println(ex);
}
}
}
答案 0 :(得分:1)
你显然可以从for循环返回。
public String getFileInformation() throws IOException {
try{
String file;
file = "tra.srt";
Charset charset = Charset.defaultCharset();
Path path = Paths.get(file);
BufferedReader reader = Files.newBufferedReader(path, charset);
System.out.printf("Lines from %s:%n",file);
String line;
while((line = reader.readLine()) != null) {
if (line.indexOf(':') != -1 && line.indexOf(',') != -1 && line.indexOf('0') != -1) {
return line.substring(0, 12);
}
}
}catch(FileNotFoundException ex){
System.err.println(ex);
}
return "";
}