【发布时间】:2016-10-16 20:12:50
【问题描述】:
我正在编写一个包含 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 条件为假,'else' 语句总是会执行。
现在,如果这些都是假的:
if(name == null || name.trim().isEmpty())
throw new Exception("The key is empty");
else if(exists(name)){
hTable.remove(name);
}
else部分不应该总是执行吗?
else throw new Exception("Animal doesn't exist");
我注意到这一点,因为此方法返回真/假,并且似乎忽略了 else 部分,即使上面的条件为假。
【问题讨论】:
-
else将在所有其他条件下触发 - 即if,if else--是false。它不会总是执行。这样想:If it is raining, then I carry my umbrella; else if it is snowing, then I wear my parka; else I wear shorts and a tshirt. -
这些不是嵌套的。它们是排序的。你的第二个 else 与你的第二个 if 相匹配。如果你想要
"Animal doesn't exist",exists(name)需要为false,而不是第一个if-condition中的条件。 -
@KennethK。 OP 询问这些(其他条件)是否为假,否则是否总是执行,那是的
-
@AndrewL 不,他写道,如果
if条件为假,而不是所有其他条件。
标签: java