Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

variable-names inside an array

Status
Not open for further replies.

bateman23

Programmer
Mar 2, 2001
145
DE
Hi,
i wonder if there is a way of storing and accessing variables inside an array.
To make things a little more clear, i used coding PHP and the following construct has been one of my favourite ones:

Code:
$checkarray=array("name", "street");
	foreach($checkarray as $value) {
		if(trim(${"$value"})=="") {
			${"error_"."$value"}="Error";
			$error++;
		} // end if
	} // end foreach

So "name" and "street" are variable-names, which i can access by ${"$value"}.
This was a wonderful way, of checking if forms have been completely filled out.
Is there any possibility doing this in java/jsp?

Thanks in advance,
Daniel
 
Never done PHP, but from the looks of it, and guessing, a direct conversion would be :

Code:
String[] checkArray = new String[] {"name", "street"};
String error = "";
int numErrors = 0;
for (int i = 0; i < checkArray.length; i++) {
	if (checkArray[i].trim().equals("")) {
		numErrors++;
		error += ("Error : " +checkArray[i]);
	}
}

--------------------------------------------------
Free Database Connection Pooling Software
 
Thanks for the hints sedj. An Array of objects did the job... - nearly

Code:
Object check[]= new Object[] {name, street}; // Array initialisieren
	for(int i=0;i<check.length;i++) {
		if(check[i].equals("")) {
			write=false;
			out.println("Error");
			// ** HERE ** here occured another problem **
		} // end if
	} // end for

Another problem, which occured is, that i'm not able to build a variable out of strings... At the line marked with ** HERE ** i want to fill an error-variable which is named "error_"+the name of the object.
For example. If the object is "name", the variable should be named "error_name",
if the object is "street" it should be called "error_street".
In PHP it's done that way:
Code:
${"error_"."$value"}="Error";
The Java code for each object would be:
Code:
error_name = "Error"; and
error_street = "Error";

so the problem is, that i have to build the variable names at runtime out of strings. (at least i think so)

---------------------------------------
Visit me @:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top