在循环中只显示一次更新提示



我只想显示一次提示。调用update函数的循环中的"Do you want to update"。

for (String person : persons) {
if (id != null && !id.equals(person.getLocalId())) {
System.out.print("ID is not same");
BufferedReader reader = new BufferedReader
(new InputStreamReader(System.in));
System.out.print("Do You Want to Update (Y/N) ? >");
try {
var ans = reader.readLine();
if (ans.equalsIgnoreCase("Y") && ans.length() > 0) {
service.update(person.id);
} else if (ans == null || ans.equalsIgnoreCase("N")) {
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
sqlSession.commit();

只要满足循环条件,就会执行循环的主体。对于"foreach"循环的特殊情况,它会为集合中的每个元素执行一次。

因此,如果你只想执行一次某个东西,你必须将它移出循环。我假设您只想在循环中调用service.update方法,而不是所有方法(即,您不想从循环内部调用System.exit(0)(。

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Do You Want to Update (Y/N) ? >");
try {
var ans = reader.readLine();
if (ans.equalsIgnoreCase("Y") && ans.length() > 0) {
for (String person : persons) {
service.update(person.id);
}
} else if (ans == null || ans.equalsIgnoreCase("N")) {
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
sqlSession.commit();

最新更新