19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

SOLUTION:<br />

Coding is simplified by using a control array of labels to hold the food names <strong>and</strong> a control array of text<br />

boxes to hold the amount input by the user. In the following template, the label captions have been<br />

assigned an initial value “(food name)” so that the labels can be seen. The five nutrients of interest <strong>and</strong><br />

the actual names <strong>and</strong> nutrient values of the foods to be used in building a meal are read from the data file<br />

NUTTABLE.TXT.<br />

Object Property Setting<br />

frmMeal Caption Nutrition in a<br />

Meal<br />

lblFood() Caption (food name)<br />

Index 0 – 9<br />

lblQnty Caption Quantity in Meal<br />

txtQnty() Text (blank)<br />

Index 0 – 9<br />

cmdAnalyze Caption Analyze Meal<br />

Nutrition<br />

picAnalysis<br />

Dim nutName(1 To 5) As String ‘nutrient names<br />

Dim nutTable(1 To 10, 1 To 5) As Single ‘nutrient values for each food<br />

Private Sub cmdAnalyze_Click()<br />

‘Determine the nutritional content of a meal<br />

Dim quantity(1 To 10) As Single ‘amount of food in meal<br />

Call GetAmounts(quantity())<br />

Call ShowData(quantity())<br />

End Sub<br />

Private Sub Form_Load()<br />

Dim i As Integer, j As Integer, foodName As String<br />

‘Fill arrays; assign label captions<br />

Open “NUTTABLE.TXT” For Input As #1<br />

For i = 1 To 5<br />

Input #1, nutName(i)<br />

Next i<br />

For i = 1 To 10<br />

Input #1, foodName<br />

lblFood(i - 1).Caption = foodName<br />

For j = 1 To 5<br />

Input #1, nutTable(i, j)<br />

Next j<br />

Next i<br />

Close #1<br />

End Sub<br />

Private Sub GetAmounts(quantity() As Single)<br />

Dim i As Integer<br />

‘Obtain quantities of foods consumed<br />

For i = 1 To 10 quantity(i) = Val(txtQnty(i - 1).Text)<br />

Next i<br />

End Sub<br />

Private Sub ShowData(quantity() As Single)<br />

Dim col As Integer, row As Integer<br />

Two-Dimensional Arrays 199

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!