DroidOS
DroidOS

Reputation: 8880

Avoiding multiple if..elseif statements

I am in the process of writing an Android app that spends a great deal of time resolving Latitude/Longitude to UTM coordinates. My current code for establishing the UTM Zone letter goes like this

if (Lat<-72) Letter='C';
else if (Lat<-64) Letter='D';
else if (Lat<-56) Letter='E';
else if (Lat<-48) Letter='F';
else if (Lat<-40) Letter='G';
else if (Lat<-32) Letter='H';
else if (Lat<-24) Letter='J';
else if (Lat<-16) Letter='K';
else if (Lat<-8) Letter='L';
else if (Lat<0) Letter='M';
else if (Lat<8) Letter='N';
else if (Lat<16) Letter='P';
else if (Lat<24) Letter='Q';
else if (Lat<32) Letter='R';
else if (Lat<40) Letter='S';
else if (Lat<48) Letter='T';
else if (Lat<56) Letter='U';
else if (Lat<64) Letter='V';
else if (Lat<72) Letter='W';
else Letter='X';

Whilst this works it appears to be a horribly inefficient way of dong things. Most of my users will be in Zone U which means as things stand the app is performing 16 failed if..elseif tests prior to establishing the right zone letter.

Easily set right by adjusting the order of the if..elseifs? True but I cannot but help thinking that there has got to be a cleaner way to do this. I am still something of a Java newbie so although have experimented with HashMaps etc I have failed to make much headway.

Is a more elegant approach possible?

Upvotes: 3

Views: 148

Answers (2)

halfer
halfer

Reputation: 20420

(Posted answer on behalf of the question author).

For the benefit of anyone else running into this question: Based on the answer @AndyTurner I ended up doing this:

public static char testIt(double lat)
{
 return "CCCDEFGHJKLMNPQRSTUVWXXX".charAt((int)(Math.ceil((lat + 90)/ 8)));
}

An explanation is in order here:

  • Adding 90 ensures that we are dealing with a nice 0-180 range that can be handled in a neater way - and probably better/faster than using Math.min/max
  • Below -72 degrees the Zone letter is always C and above 72 degrees it is always X. Rather than deal with these issues by putting in an if.. test we simply artifically extend the zone letter range at either end by padding it with extra Cs and Xs as required.

A handy graphical reference for checking the validity of the result is this UTM grid chart. I have coded my own test here.

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140299

  char Letter = "CDEFGHJKLMNPQRSTUVWX".charAt((int)((Lat + 80) / 8);

perhaps with some clamping to ensure that Lat is in a suitable range (an alternative being throwing an exception, since UTM is undefined outside this range):

  ClampedLat = Math.min(Math.max(Lat, -80), 84);

Upvotes: 8

Related Questions