有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的函数即使有一个条件出错也返回true?

在Java中,我有两个函数一起工作以返回布尔条件。两者都是从继承类Serie和Filme的类Programa中获取对象。只有当试图创建的项目与已有的项目具有相同的名称+相同的类别+相同的类时,它们才应该返回true,但当我具有相同的名称,并且在其他类中具有相同的类别时,它们仍然返回true

例:姓名:Doe,喜剧类,意甲 我不能做“名字:多伊,类别喜剧,电影”

你能看出我错在哪里吗

    public boolean seExiste(Programa programa) {
        for (Programa y : this.programa) {
            if (Serie.class.isInstance(y) && y.getNome().equals(programa.nome)
                    && y.getCategoria().equals(programa.categoria)) {
                return true;
                
            } if (Filme.class.isInstance(y) && y.getNome().equals(programa.nome)
                    && y.getCategoria().equals(programa.categoria)) {
                return true;
            }                   
        }
        return false;
    }
public void cadastrar(Programa programa) {
        if (!seExiste(programa)) {
            // System.out.println(programa.hashCode());
            this.programa.add(programa);
        } else {
            System.err.println("ERROR");
        }
    }

共 (2) 个答案

  1. # 1 楼答案

    电影和意甲之间有传承吗?在这种情况下,如果一个意甲是一部电影(意甲延伸了电影),那么意甲。班isInstance(filmeObject)将始终为false,并将被拍成电影。班isInstance(serieObject)将为真

    isInstance方法决定对象(参数)是否与类兼容

    如果对象扩展了类(静态类型是类)或实现了类(静态类型是接口),则对象的动态类型与类(静态类型)兼容

  2. # 2 楼答案

    这就是你正在做的。当您返回true时,您将不知道它是Filme还是Serie。也许您应该返回1,2或-1的int,或者使用enum来指示所评估的内容

    public boolean seExiste(Programa programa) {
        for (Programa y : this.programa) {
            
            // here is the common condition.
            // this must be true to return true.
            // otherwise the loop continues. Notice the ! that inverts the expression.
            if (!(y.getNome().equals(programa.nome)
                    && y.getCategoria().equals(programa.categoria))) {
                continue;  // skip next if and continue loop
            }
            // if the the categoria and nome match then check the instance.   
            if (Filme.class.isInstance(y) || Serie.class.isInstance(y)) {
                return true;
            }           
        }
        return false;
    }