The Artima Developer Community
Sponsored Link

Java Answers Forum
Array and for loop issue

2 replies on 1 page. Most recent reply: Aug 16, 2007 11:41 AM by Dave H

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
joe douglas

Posts: 3
Nickname: oaklander
Registered: Aug, 2007

Array and for loop issue Posted: Aug 14, 2007 6:48 PM
Reply to this message Reply
Advertisement
I have this JSP where I have alot of fields with conditions.
I would like to make it more efficient and use a for loop.
Here is an example (showing 2 fields for example only):

<%@ page language="java" import="java.util.*" %>
<%
HashMap errors = new HashMap();
String firstname = "Joe";
String lastname = "Miller";

if (!firstname.equals(""))
{
errors.put("firstname",firstname);
}
if (!lastname.equals(""))
{
errors.put("lastname",lastname);
}

out.println(errors.get("firstname"));
out.println(errors.get("lastname"));
%&g t;



It prints out Joe Miller

Now my attempt below to put this in a loop prints out null null:

<%@ page language="java" import="java.util.*" %>
<%
HashMap errors = new HashMap();
String firstname = "Joe";
String lastname = "Miller";
//String[] keys = {"firstname", "lastname"};
String[] keys = {firstname, lastname};
for(int i = 0;i < keys.length;i++)
{
if(!keys[i].equals(""))
{
errors.put(keys[i],keys[i]);
}
}

out.println(errors.get("firstname"));
out.println(errors.get("lastname"));

%>


Please advise.


Dave H

Posts: 16
Nickname: slebtack
Registered: Apr, 2007

Re: Array and for loop issue Posted: Aug 15, 2007 5:56 AM
Reply to this message Reply
You are confusing the name of the variable with the value of the variable.

<%@ page language="java" import="java.util.*" %>
<%
HashMap errors = new HashMap();
String firstname = "Joe";
String lastname = "Miller";
String[] keys = {"firstname", "lastname"};
String[] values = {firstname, lastname};
for(int i = 0;i < keys.length;i++)
{
if(!keys[i].equals(""))
{
errors.put(keys[i],values[i]);
}
}

out.println(errors.get("firstname"));
out.println(errors.get("lastname"));

%& gt;

(Untested.)

Dave H

Posts: 16
Nickname: slebtack
Registered: Apr, 2007

Re: Array and for loop issue Posted: Aug 16, 2007 11:41 AM
Reply to this message Reply
…where if(!keys[i].equals("")) should be if(!values[i].equals(""))

I told you it was untested.

Flat View: This topic has 2 replies on 1 page
Topic: Array and for loop issue Previous Topic   Next Topic Topic: Getting the aknowledge / read confirmation

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use