java - 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;
}
解决方案
从逻辑上分析,您的 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;
}
推荐阅读
- google-apps-script - Sheets插件中Google Scripts Time-Based Trigger的问题总是失败
- javascript - 循环内的 HTML 元素处理 - 使用 JS
- javascript - 如何在javascript Object.defineProperty 中定义数组的getter 函数?
- count - 包括切片机的Countrows
- windows - 使用 docker 发出正在运行的项目
- android - Android 警报对话框单元测试
- sql - SQL 新手,在尝试测试触发器时出现“在数据库 'flowers2019' 上执行 SQL 查询时出错:没有这样的列:SIGHTINGS.PERSON”
- javascript - 使用 Dropzone 和 Laravel 上传产品
- angular - 为什么商店状态的变化没有广播到我的组件
- jquery - 如何在数组中动态传递列值并通过数组索引设置值