java - How to use an if function to call elements of an array -


basically, have variable 'prime'. can take values between 0 , 6. based on value, want string 'result' sunday if prime 0, monday if 1, etc. currently, it's coded way:

string result = new string();      if (prime == 0)     {         result = "sunday";     }      if (prime == 1)     {         result = "monday";     }      if (prime == 2)     {         result = "tuesday";     }      if (prime == 3)     {         result = "wednesday";     }      if (prime == 4)     {         result = "thursday";     }      if (prime == 5)     {         result = "friday";     }      if (prime == 6)     {         result = "saturday";     }      else     {         result = "check code.";     } 

i'm wondering if there's faster way this? i've created array days of week:

string[] days = new string[7];      days [0] = "sunday";     days [1] = "monday";     days [2] = "tuesday";     days [3] = "wednesday";     days [4] = "thursday";     days [5] = "friday";     days [6] = "saturday"; 

how , elegantly code if value of prime 0, string 'result' first element of array, , on until if prime 6, string 'result' seventh element?

you have valid values stored in simple lookup table, need ensure requested value within range of available values.

the basic answer like...

if (prime >= 0 && prime < days.length) {      result = days[prime];  } else {     result = prime + " not within valid range";     // or throw exception } 

what makes sure prime value within valid range of acceptable values (0..days.length - 1), other wise returns error message (or throw exception).

remember, arrays 0 indexed, hence need use < days.length (less then) , not <= days.length (less or equals to)


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -