At times, starting an array with an index value of 0 seems counter-intuitive. For example, do users really think of Monday as the zeroth day of the week, or do they think of Monday as the first day of the week? I vote for the second option. Indeed, when a user runs the program shown in Figure 7.1 for the first time, he or she probably wouldn't even think of entering a zero for the index value, even though the label for the text box tells the user that Monday equates to 0. This points out a programming truism: Users don't read program labels.
Whether the users read the labels or not, it would be nice to define the array in a way that is consistent with the way you expect to use the array. In the day-of-the-week program, it would make more sense to have Monday have an index value of 1 than an index value of . There are several ways to accomplish this. First, you could change the code to make it look like the following:
Dim DaysOfTheWeek(7) As String DaysOfTheWeek(0) = "" DaysOfTheWeek(1) = "Monday" DaysOfTheWeek(2) = "Tuesday" DaysOfTheWeek(3) = "Wednesday" ' ...and so on for the other days...
In this solution, you dimension the array for one additional element and assign an empty string to element . The good news is that Monday now has an index value of 1 . The bad news is that you've wasted the memory associated with element . The other bad thing about this approach is that, even though you never intend to use element , because it is there, you could inadvertently use it in a program. As you gain more programming experience, you will find that program bugs often hide in good intentions such as these.
I refer to code like this as RDC (that is, really dumb code) because it wastes memory and it's a potential breeding ground for bugs. Nope, it is not a good solution to the problem. You are better off sticking with your original code, with a minor modification.
First, you need to change the text in the label for the txtIndex text box to this:
Enter number for Day of the Week (Monday = 1)
Next, you need to change the program line that indexes into the DaysOfTheWeek() array to the following:
txtDay.Text = DaysOfTheWeek(CInt(txtIndex.Text) - 1)
Note that the only change here is that you subtract 1 from the array index value typed in by the user. Now, when the user enters 1 for the first day of the week, the statement processes the information as follows :
txtDay.Text = DaysOfTheWeek(CInt(txtIndex.Text) - 1) txtDay.Text = DaysOfTheWeek(CInt("1") - 1) txtDay.Text = DaysOfTheWeek(1 - 1) txtDay.Text = DaysOfTheWeek(0) txtDay.Text = "Monday"
This minor program change leads to a much more intuitive interface for the user. The days of the week now run from 1 through 7, which makes more sense than a range of 0 through 6. Two relatively minor program changes have made the program a little bit easier for the user to understand.