DroidOS DroidOS - 4 months ago 12
Java Question

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.

I hope that someone here might be able to suggest a more elegant approach.

++++++

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)
{
lat = Math.min(Math.max(lat, -72), 72);
if ((72 <= lat) || (-72 >= lat)) return 'X';
return "CDEFGHJKLMNPQRSTUVWX".charAt((int)((lat + 80) / 8));
}


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

Answer
  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);
Comments