表驱动法


直接访问表

例子一:将数组作为表

// 下面原先的方法,是一个长长的swtich语句
String today = "周日";
Switch( dayForMonth % 7 ){
    case 0 : 
        today = "周日";
    case 1 : 
        today = "周一";   
    case 2 :
        today = "周二";   
    case 3 :
        today = "周三";   
    case 4 :
        today = "周四";   
    case 5 :
        today = "周五";   
    default:
        today = "周六";   
}
// 使用表驱动
// 使用一个数组去存入一周的日期
String [] weekday = new String[]{"周日","周一","周二","周三",
    "周四","周五","周六"};
String today = weekday [ dayForMonth % 7 ];

例子二

int iGetMonthDays(int iMonth)
{
int iDays;
if(1 == iMonth) {iDays = 31;}
else if(2 == iMonth) {iDays = 28;}
else if(3 == iMonth) {iDays = 31;}
else if(4 == iMonth) {iDays = 30;}
else if(5 == iMonth) {iDays = 31;}
else if(6 == iMonth) {iDays = 30;}
else if(7 == iMonth) {iDays = 31;}
else if(8 == iMonth) {iDays = 31;}
else if(9 == iMonth) {iDays = 30;}
else if(10 == iMonth) {iDays = 31;}
else if(11 == iMonth) {iDays = 30;}
else if(12 == iMonth) {iDays = 31;}
return iDays;
}
static int aiMonthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
// 我们可以先定义一个静态数组,这个数组用来保存一年十二个月的天数
int iGetMonthDays(int iMonth)
{
return aiMonthDays[(iMonth - 1)];
}



Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • 2379. Minimum Recolors to Get K Consecutive Black Blocks
  • 2471. Minimum Number of Operations to Sort a Binary Tree by Level
  • 1387. Sort Integers by The Power Value
  • 2090. K Radius Subarray Averages
  • 2545. Sort the Students by Their Kth Score