首页 > 解决方案 > java中的while循环总是返回true

问题描述

无论他输入是否为真,我的 while 循环都会返回真。所以它使用dao中的id方法检查director是否存在。一旦它更改为 false 并且 id 不存在,while 循环应该结束。id 从 1 开始进行第一次迭代。d F Name 和 d S Name 接受第一个 id 1。如果当前的 director 名称不等于正在创建的新 director,它应该将 id 增加 1。如果它们不匹配,它应该简单地返回“真的”。如果它是 else 选项,那么它应该只是将 id 再次增加 1 并返回到循环中。这应该一直持续到第一个不存在的 Id 或找到重复的名称。

在我看来,它没有在第一个 if 语句中运行 if 语句,而是直接跳到嵌套在第一个 if 语句中的 if 语句。我已经尝试使用 do...while(),仅使用 if 语句和没有 if 且没有更改的 while 语句围绕循环进行更改。

This is the loop I am working on. 
   

public boolean checkDirectorNameIsNotDuplicate(Director director) {
        int id = 1;
        String dFName;
        String dSName;
            while(directorDao.existsById(id)==true) {
                dFName = directorDao.getDirectorFirstNameById(id);
                dSName = directorDao.getDirectorSurnameById(id);
                if (!director.getDirectorFirstName().equals(dFName) && !director.getDirectorSurname().equals(dSName)){// if directorFirstName is not equal to dFName AND directorSurname is not equal to dsname
                        id++; //move to next Id
                        System.out.println(id);
                        }
                else {
                            if (director.getDirectorFirstName().equals(dFName) && director.getDirectorSurname().equals(dSName)) {
                                return true;
                            }
                            else {
                                id++;
                            }
                    }
                }
            return false;
    }

标签: javaspringloopswhile-loop

解决方案


从逻辑上分析,您的 if-else 语句中的某些内容是多余的。最好删除一些语句并更改为以下代码,该代码只是从您的代码中进行的简单修改。

此外,您的变量id没有结束条件,这可能导致无限循环。

public boolean checkDirectorNameIsNotDuplicate(Director director) {
    int id = 1;
    String dFName;
    String dSName;
    while(directorDao.existsById(id)) {
        dFName = directorDao.getDirectorFirstNameById(id);
        dSName = directorDao.getDirectorSurnameById(id);

        if (director.getDirectorFirstName().equals(dFName) && director.getDirectorSurname().equals(dSName)) {
            return true;
        }
        else {
            id++;
            System.out.println(id);
            
            // add condition here to void an infinite loop
            if (/*something to do with id*/) {
                break;
            }
        }
    }
    return false;
}

推荐阅读