How do I make strings into string variables in Java?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Shelleen_Qian
Posted On:   Thursday, November 7, 2002 10:19 AM

This is what I'm doing:

			
String str; //str is read from input stream.
String name,
address;
...
if (str == "name")
name = str;
else
if (str == "address")
address = str;
else
...

Instead of doing nesting if else I want to have better way to make strings into variables. I think it must be something simple.


Thanks,

Shelleen

Re: How do I make strings into string variables in Java?

Posted By:   michael_dean  
Posted On:   Thursday, November 7, 2002 02:12 PM

I'm not sure what your goal is, but maybe this will help...



If you're comparing object "identity" (i.e. are two object references pointing to the same object), you use:




if (objectReference1 == objectReference2) { ... }


If you're comparing object "state" (i.e. the contents of the fields of the objects), you use:




if (objectReference1.equals(objectReference2) { ... }


So your code above is checking to see if two object references point to the same object and, if so, reassigns one to point to the other (which, we just learned is the only object we're dealing with--i.e. it's equivalent to saying objectReference1 = objectReference1;).



If you're actually doing equality testing, i.e.:




String str; //str is read from input stream.
String name,
address;
...
if ("name".equals(str)) {
name = str;
} else if ("address".equals(str)) {
address = str;
} else {
...
}


Then, all you've done is taken the long route to intern the String read from an input stream (which might be what you're looking for?).



If you're not trying to intern the String (or if you don't know what that means), then essentially, the conditional has done nothing for you. If you're trying to assign a value to name if the String you read contains "name" you would need code similar to:




String str; //str is read from input stream.
String name,
address;
...
String lowerCaseVersionOfStr = str.toLower();
if (lowerCaseVersionOfStr.indexOf("name") != -1) {
name = str;
} else if (lowerCaseVersionOfStr.equals("address") != -1) {
address = str;
} else {
...
}


If you're looking for an object-oriented means to replace long if ... else if ... else if blocks, I suggest taking a look at some Object Oriented Programming or Object Oriented Design books.



HTH.

About | Sitemap | Contact