英文:
Display prompt only once for update inside a loop
问题
我想要在循环中仅显示一次提示:“你想要更新吗”,该循环调用更新函数。
for (String person : persons) {
if (id != null && !id.equals(person.getLocalId())) {
System.out.print("ID不相同");
BufferedReader reader = new BufferedReader
(new InputStreamReader(System.in));
System.out.print("您是否要进行更新(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();
英文:
I would like to display the prompt only once. "Do you want to update" inside a loop which calls the update function.
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();
答案1
得分: 0
循环的主体在循环条件满足的情况下执行。对于特殊情况下的“foreach”循环,它会针对集合中的每个元素执行一次。
所以,如果您想要执行某些操作仅一次,您必须将其移出循环。我假设您只想在循环中调用service.update
方法,而不是所有内容(即您不想从循环内部调用System.exit(0)
)。
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("是否要更新 (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();
英文:
The body of a loop is executed as long as the loop condition is satisfied. For the special case of a "foreach" loop, it is executed once for each element in a collection.
So if you want to execute something only once, you have to move it out of the loop. I assume you only want to call the service.update
method in a loop, not everything (i.e. you do not want to call System.exit(0)
from inside your loop).
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();
专注分享java语言的经验与见解,让所有开发者获益!
评论