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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Alternative approach for the following task

Status
Not open for further replies.

shylaja

Programmer
Feb 13, 2003
4
IN
Hi
I need a alternative approach for the following code segment.
I have a task where a particular string has to be checked if it is one among the following values
(byte,boolean,string,char,int,float,doublee);
I have used if else logic to check that value and the code is as follows
if(!names.equalsIgnoreCase("byte")){
if(!names.equalsIgnoreCase("boolean")){
if(!names.equalsIgnoreCase("char")){
if(!names.equalsIgnoreCase("int")){
if(!names.equalsIgnoreCase("double")){
if(!names.equalsIgnoreCase("float")){
if(!names.equalsIgnoreCase("short")){
if(!names.equalsIgnoreCase("long")){
return true;

}
}

}
}
}
}
}
}
Can any other alternative way can be used to code this , so that the code becomes simpler .

Thanks in advance
shylaja
 
Code:
class Findit{
	protected static java.util.Hashtable _types = new java.util.Hashtable();
	static protected String[] _stypes = {
		"byte","char","int","short","long","double","float","boolean" };
		
	static{
		for(int n=0; n<_stypes.length; n++)
			_types.put( _stypes[n], _stypes[n]);
	}
	
	public static boolean find(String type){
		String ltype = type.toLowerCase();
		return _types.containsKey(ltype);
	}
	
	public static void unitTest(){
		String test[] = {&quot;int&quot;,&quot;integer&quot;,&quot;Short&quot;,&quot;bool&quot;,&quot;douBle&quot;};
		for(int n=0; n<test.length; n++)
			System.out.println( test[n] + &quot; found: &quot; + Findit.find(test[n]));
	}
}

That was fun B-)
-pete

 
A similar approach to Pete's but perhaps a shade simpler:

static String [] keywords =
{&quot;boolean&quot;, &quot;byte&quot;, &quot;char&quot;, &quot;double&quot;, float&quot;,
&quot;int&quot;, &quot;long&quot;, &quot;short&quot;}; // MUST be ordered alphabetically

int i; // Index

i = java.util.Arrays.binarySearch(keywords, names.toLowerCase());

if (i >= 0)
{
switch (i)
{
case 0: // &quot;boolean&quot;
...
break;

case 1: // &quot;byte&quot;
...
break;

case 2: // &quot;char&quot;
...
break;

etc ...
} // end Switch
} // end if
else
{
// Not found
}
 
Hi
I tried out both the approaches .Both the approaches was helpful.

Thanks
Shylaja
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top