出现以下错误,我不知道如何解决:
This method must return a result of type String
当“String result = fileRead(0, "months.txt");”时,程序应该打印文件“months.txt”的所有行= 0。当我指定要输出的行时,它可以在没有巨大的 if-else 的情况下工作,但我不知道如何让它像这样工作,
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class methodsExceptions1 {
public static void main(String[] args) throws IOException {
String result = fileRead(0, "months.txt");
System.out.println(result);
}
public static String fileRead(int line, String f) throws IOException {
File myFile = new File("months.txt");
Scanner inputFile = new Scanner(myFile);
if (line == 0 && inputFile.hasNextLine()) {
System.out.println(inputFile.nextLine());
} else {
String lineRead = "";
for (int i = 0; i < line; i++) {
if (inputFile.hasNextLine()) {
lineRead = inputFile.nextLine();
} else {
return "FILE READ ERROR: There are only " + i + " lines of text in this file";
}
}
inputFile.close();
return lineRead;
}
}
}
答案 0 :(得分:0)
您的方法仅返回 else
分支中的字符串。如果 line == 0 && inputFile.hasNextLine()
为真,则不返回任何内容。
要修复错误,请在正分支中返回一些内容,或者抛出异常。
也许您打算返回 inputFile.nextLine()
而不是打印它。
答案 1 :(得分:0)
如果将 return
语句放在 if 或 if-else 或 else 块中,则会出现此类错误。
因此,您还应该从这些块中编写一个 return
语句。 (另外,一些编辑器会在编码过程中屏蔽此代码)
public class MethodsExceptions1 {
...
...
public static String fileRead(int line, String f) throws IOException {
File myFile = new File("months.txt");
Scanner inputFile = new Scanner(myFile);
if(line == 0 && inputFile.hasNextLine()) {
System.out.println(inputFile.nextLine());
}else {
String lineRead = "";
for (int i = 0; i < line; i++) {
if (inputFile.hasNextLine()) {
lineRead = inputFile.nextLine();
} else {
return "FILE READ ERROR: There are only " + i + " lines of text in this file";
}
}
inputFile.close();
return lineRead;
}
//need a return statement here
return new String("");
}
}
答案 2 :(得分:0)
你的方法是骗子。根据它的签名,您会期望它从文件中读取一些内容并将其作为 String 对象返回。但在一种情况下,它不返回任何内容并向控制台打印一些内容。他在骗你。避免您的方法产生副作用。
如果您的方法只返回一个字符串,您可以改进这一点。让方法的调用者决定是否应打印此字符串。
代替
if (line == 0 && inputFile.hasNextLine())
System.out.println(inputFile.nextLine());
做
if (line == 0 && inputFile.hasNextLine()) {
return inputFile.nextLine();