如果名字已经存在,那么我想为该特定人员替换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", "[email protected]", 1000000.00);
Celebrity c2 = new Celebrity("Michal", "Jackson", "king of [email protected]", 1000000000.00);
Celebrity c3 = new Celebrity("Aaron", "Hoffman", "[email protected]", 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;
}
}
我认为您的代码非常混乱,但是似乎“中断”未放置在正确的位置。如果要更新属性(uf,我不喜欢可变对象,但这是我的看法),然后停止,只需将“ break”移动到第一个“ if”
如果(list.get(i).getEmail()。equalsIgnoreCase(firstName))