gpt4 book ai didi

java - 如何用新值替换现有值

转载 作者:行者123 更新时间:2023-12-01 22:34:08 24 4
gpt4 key购买 nike

如果名字已经存在,那么我想替换该特定人的 NetWOrth 值,而不重复旧值。

我在循环列表时尝试这样做,但它给了我一个重复的条目。

List<Celebrity> list = new CopyOnWriteArrayList<Celebrity>();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");

Celebrity cl = new Celebrity("Frank", "Sinatra", "franks.inatra@smoothjazz.com", 1000000.00);
Celebrity c2 = new Celebrity("Michal", "Jackson", "king of pop@mtv.com", 1000000000.00);
Celebrity c3 = new Celebrity("Aaron", "Hoffman", "jamsonreal@smoothjazz.com", 10000.00);

list.add(cl);
list.add(c2);
list.add(c3);

String firstName = request.getParameter("first");
String lastName = request.getParameter("last");
String email = request.getParameter("email");
double netWorth = Double.parseDouble(request.getParameter("netWorth"));


for (int i = 0; i < list.size(); i++) {
if (list.get(i).getEmail().equalsIgnoreCase(firstName)) {
list.get(i).setNetWorth(netWorth);
}

if (!list.get(i).getFirstName().equalsIgnoreCase(firstName)) {
list.add(new Celebrity(firstName, lastName, email, netWorth));
break;
}
}
}

最佳答案

我不明白为什么你将电子邮件与名字进行比较:

 ...
if (list.get(i).getEmail().equalsIgnoreCase(firstName)) {
...

如果我理解正确的话,这可能是您问题的解决方案:

  for(Celebrity  ce:list){
if (ce.getFirstName().trim().equalsIgnoreCase(firstName.trim()) &&ce.getNetworth!=netWorth){
ce.setNetworth(networth);
break;
}
}

关于java - 如何用新值替换现有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58535554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com