PDA

View Full Version : Loop needed to condense bean class


florida
08-17-2007, 02:28 AM
I have some code that works great in my Bean class that looks like the below where I have around 15 fields. For example I condensed it to 2 fields:

//bean model part
HashMap errors = new HashMap();
String firstname = "Joe";
String lastname = "Miller";

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


//Each field is then called like this in a View page:
errors.get("firstname"));
errors.get("lastname"));


Anyway I can create a loop to go through all 15 fields or how is the best way to do this??

//use Array or Iterator or List or what to get the 15 fields then loop?
for(int i= 0;i < 15;i++)
{
/*
how would I make this part work?
if (firstname.equals(""))
{
errors.put("firstname","missing firstname".);
}
if (lastname.equals(""))
{
errors.put("lastname","missing lastname");
}
*/
}


Please advise.

jkim
08-20-2007, 03:59 AM
in order to do what you want, you'd need the variables as a part of a list / array structure.

i.e.

//bean model part
HashMap errors = new HashMap();
Hashtable variables = new Hashtable();

...

variables.add("firstname", "Joe");
variables.add("lastname", "Miller");

...
{
String key = null;
String value = null;
Enumeration k = variables.keys();
while (k.hasMoreElements()) {
key = (String)k.nextElement();
value = variables.get(key);
if ("".equals(value)) { // or: if ((value != null) && (value.equals(""))) {
errors.put(key, "missing " + key);
}
}
}
...