Table-Driven Approach - a more elegant form of if-else or switch-case
Table-Driven Approach
Table-Driven Approach
- Direct Table Access Calculate the number of days in each month.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
if(month == 1) { days = 31; } else if (month = 2){ days = 28; } else if (month = 3){ days = 31; } else if (month = 4){ days = 30; } else if (month = 5){ days = 31; } else if (month = 6){ days = 30; } else if (month = 7){ days = 31; } else if (month = 8){ days = 31; } else if (month = 9){ days = 30; } else if (month = 10){ days = 31; } else if (month = 11){ days = 30; } else if (month = 12){ days = 31; }Save this data into a table and create this table:
1
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
1
charType = charTypeTable[inputChar];
本文由作者按照 CC BY 4.0 进行授权