Re: Array reference in for loop
IchBin wrote:
teser3@hotmail.com wrote:
I have a validate method in a bean class that works and now I want to
condense it into a for loop.
Here is what I have:
//firstname and lastname are declared earlier
public boolean validate()
{
boolean allOk=true;
if (firstName.equals("")) {
errors.put("firstName","Please enter your first name");
allOk=false;
}
if (lastName.equals("")) {
errors.put("lastName","Please enter your last name");
allOk=false;
}
return allOk;
}
My attempt doesnt work because I cant seem to figure out how to put
the array reference in the key part of the errors.put method:
public boolean validate()
{
boolean allOk=true;
String [] myarray = {firstname, lastname}
for(int i=0;i < myarray.length;i++)
{
if (myarray[i].equals("")) {
errors.put(myarray[i],"Please enter your " + myarray[i]);
allOk=false;
}
}
return allOk;
}
The results dont validate any of my data so I assume I have something
wrong with my array. Please advise.
Quick and dirty:
public boolean validate()
{
boolean allOk=true;
String [] myarray = {firstName, lastName,
"first Name","last Name"};
for(int i=0;i < myarray.length;i++){
if (myarray[i].equals("")) {
errors.put(myarray[i] + " Please enter your " +
myarray[i+2]);
allOk=false;
}
}
return allOk;
}
There are two needs for a String array, providing the labels for using
in the message and holding the input. Why not use two arrays, one for
each job?
public boolean validate()
{
boolean allOk=true;
String[] input = {firstName, lastName};
String[] labels = {"first Name","last Name"};
for(int i=0;i < input.length;i++){
if (input[i].equals("")) {
errors.put(input[i] + " Please enter your " +
labels[i]);
allOk=false;
}
}
return allOk;
}
I don't like names like "myarray", because they are often associated
with constructs that do not have a single clear purpose.
Patricia