Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 375
DroidOS Avatar asked Mar 09 '26 21:03

DroidOS


1 Answers

  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);
like image 91
Andy Turner Avatar answered Mar 11 '26 11:03

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!