Java布尔返回语句

时间:2015-03-03 01:30:45

标签: java boolean return

我试图编写一个程序,如果文件索引不存在,将打印出一条失败消息。当我把这段代码放入BlueJ时,它告诉我需要一个return语句。帮助

public boolean validIndex(int index)
    {
        if ((index >= 0) && (index <= files.size() - 1)) {
            return true;
        }
        else {
            System.out.println("File not found.");
        }
    }

3 个答案:

答案 0 :(得分:0)

在你的else语句中应该是,&#34;返回false&#34;。

如果您正在执行 - public String validIndex(int index)  您可以返回尝试输出的消息,即: System.out.println(&#34;找不到文件。&#34;);

答案 1 :(得分:0)

您尚未为else语句添加return l。添加if else语句或else语句中的返回值

public boolean validIndex(int index) {
 if ((index >= 0) && (index <= files.size() - 1)) {
 return true; 
} else {
 System.out.println("File not found.");
 }
return false; 
 }

答案 2 :(得分:0)

您应该在else中返回一些内容。您已将返回类型指定为boolean,因此该方法应始终返回boolean

public boolean validIndex(int index)
{
        if ((index >= 0) && (index <= files.size() - 1)) {
            return true;
        }
        else {
            System.out.println("File not found.");
            return false;
        }
}