【问题标题】:Java: if, else and returnJava:如果、否则和返回
【发布时间】: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 将在所有其他条件下触发 - 即ifif 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


【解决方案1】:

在不知道代码的其余部分exists(String name)hTable (Map<String,? extends Object>) 的类型的情况下,我需要猜测:

如果 exits 返回 true,则 else if 语句的计算结果为 true。将执行 hTable.remove(name) 行。 else-branch 没有被调用,因为 else if 被调用了。现在最后一行将return hTable.get(name) == null;

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

【讨论】:

    【解决方案2】:

    我会尝试将 cmets 添加到您的 sn-p 以帮助您了解流程:

    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
    }
    

    希望cmets能帮助你理解流程!

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 2017-08-23
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多