Java 如何用新值替换现有值
如果名字已经存在,那么我希望替换该特定人员的NetWOrth值,而不重复旧值 我在循环浏览列表时尝试这样做,但它给了我一个重复条目Java 如何用新值替换现有值,java,servlets,Java,Servlets,如果名字已经存在,那么我希望替换该特定人员的NetWOrth值,而不重复旧值 我在循环浏览列表时尝试这样做,但它给了我一个重复条目 List<Celebrity> list = new CopyOnWriteArrayList<Celebrity>(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOExc
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;
}
}
}
List List=new CopyOnWriteArrayList();
受保护的void doGet(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException{
response.setContentType(“text/html”);
名人cl=新名人(“弗兰克”、“西纳特拉”、“法兰克”。inatra@smoothjazz.com", 1000000.00);
名人c2=新名人(“迈克尔”、“杰克逊”、“国王”pop@mtv.com", 1000000000.00);
名人c3=新名人(“艾伦”、“霍夫曼”、“阿伦”jamsonreal@smoothjazz.com", 10000.00);
列表。添加(cl);
增加(c2);
增加(c3);
String firstName=request.getParameter(“first”);
字符串lastName=request.getParameter(“last”);
字符串email=request.getParameter(“email”);
double-netWorth=double.parseDouble(request.getParameter(“netWorth”);
对于(int i=0;i
我不明白你为什么要将电子邮件与名字相比较:
...
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;
}
}
我认为您的代码非常混乱,但似乎“break”没有放在正确的位置。如果要更新属性(uf,我不喜欢可变对象,但这是我的意见),然后停止for,只需将“break”移动到第一个“If”
如果(list.get(i).getEmail().equalsIgnoreCase(firstName))我建议不要使用原始
list
而使用list
。很抱歉,这是打字错误。。我正在使用-----------------List List=new CopyOnWriteArrayList();我被困在状态部分。。。。