Java:if、else和return

Java:if、else和return,java,Java,我正在编写一个方法,其中包含if-else语句,但也包含一个return关键字。现在,我在写这样的东西: public boolean deleteAnimal(String name) throws Exception{ if(name == null || name.trim().isEmpty()) throw new Exception("The key is empty"); else if(exists(name)){ hTable.r

我正在编写一个方法,其中包含if-else语句,但也包含一个return关键字。现在,我在写这样的东西:

public boolean deleteAnimal(String name) throws Exception{
    if(name == null || name.trim().isEmpty())
        throw new Exception("The key is empty");
    else if(exists(name)){
        hTable.remove(name);
    }
    else throw new Exception("Animal doesn't exist");

    return hTable.get(name) == null;
}
我是java新手,这是我第一次尝试学习编程语言。我读到,如果if条件为false,“else”语句总是例外

现在,如果这些都是假的:

if(name == null || name.trim().isEmpty())
        throw new Exception("The key is empty");
    else if(exists(name)){
        hTable.remove(name);
}
其他部分不应该总是很可爱吗

else throw new Exception("Animal doesn't exist");

我注意到了这一点,因为此方法返回true/false,并且它似乎忽略了else部分,即使上面的条件为false。

在不知道其余代码的情况下
存在(字符串名称)
以及
hTable
Map
)的类型,我需要猜测:

If exits返回true,else If语句的计算结果为true。将执行hTable.remove(name)行。else分支未被调用,因为
else if
已被调用。现在,最后一行将
返回hTable.get(name)==null


我认为它将返回true,因为hTable将返回null。

我将尝试向您的代码片段添加注释,以帮助您理解流程:

public boolean deleteAnimal(String name) throws Exception{
    if(name == null || name.trim().isEmpty())
        throw new Exception("The key is empty");   //Executes if 'name' is null or empty

    else if(exists(name)){
        hTable.remove(name);       // Excecutes if 'name' is not null and not empty and the exists() returns true
    }

    else 
        throw new Exception("Animal doesn't exist");  //Excecutes if 'name' is not null and not empty and the exists() returns false

    return hTable.get(name) == null;    //The only instance when this is possible is when the 'else if' part was executed
}
希望这些评论能帮助你理解流程


考虑到这一点,您的问题的答案是“是”。

您介意发布一条消息吗?如果所有其他条件(即
if
if else
)为
false,则
将触发
else
。它并不总是执行。这样想:
如果下雨,我就带伞;否则如果下雪,我就穿上我的皮大衣;否则我会穿短裤和T恤。
它们不是嵌套的。它们是按顺序排列的。你的第二个else和第二个if一起。如果希望
“动物不存在”
存在(名称)
需要为false,而不是第一个If条件中的条件。@KennethK。OP询问这些(其他条件)是否为false,否则将始终执行,这将是yes@AndrewL不,他写的是if
if
条件是否为false,而不是所有其他条件。