admdll dll-excel2003官方

visual basic下载
2023年4月6日发(作者:skype聊天)

ingaSortedArraywithArrayMethodBinarySearch

Linearsearchesworkwellforsmallorunsortedarrays,but,forlargeunsortedarrays,

rrayissorted,thehigh-speedbinarysearch

techniquecanbeusedwithclassArray’that

demonstratesmethodBinarySearchisnearlyidenticaltotheoneinFig.7.14,sowe

pletecodeislocatedintheFig07_15folderwith

thischapter’forthisapp

isidenticaltotheoneinFig.7.13.

a)Creatingrandomvaluestosearch

b)Searchingforavaluethatisinthearray

c)Searchingforavaluethatisnotinthearray

searchofanarray.

AsinFig.7.14,theuserclickstheCreateDataButtontogeneraterandomvalues.

FormethodBinarySearchtoperformcorrectly,

createDataButton_ClickusesthefollowingcalltoArraymethodSortbeforedisplaying

thevaluesinthedataListBox:

(searchData)'sortarraytoenablebinarysearching

InmethodsearchButton_Click,wereplacedlines40–48ofFig.7.14with

DimindexAsInteger=Search(searchData,searchKey)

whi

methodreceivestwoarguments—thesortedintegerarraysearchData(thearraytosearch)

andintegersearchKey(thesearchkey).Ifthevalueisfound,methodBinarySearch

returnstheindexofthesearchkey;otherwise,itreturnsanegativenumber.

gularArrays

Thearrayswe’vestudiedsofarareone-dimensionalarrays—theycontainalistofvalues

section,weintroduce

multidimensionalarrays,whichrequiretwoormoreindicestoidentifyparticular

entrateontwo-dimensionalarrays—alsoknownasrectangular

arrays—whichareoftenusedtorepresenttablesofvaluesconsistingofdataarrangedin

rowsandcolumns(Fig.7.16).Eachrowisthesamesize,andeachcolumnisthesame

size(hencetheterm―rectangular‖).Toidentifyaparticulartableelement,wespecifytwo

indices—byconvention,thefirstidentifiestheelement’srow,thesecondtheelement’s

7.16illustratesarectangulararray,a,containingthreerowsandfour

ngulararraywithmrowsandncolumnsiscalledanm-by-narray;the

arrayinFig.7.16isa3-by-4array.

-dimensionalarraywiththreerowsandfourcolumns.

EveryelementinarrayaisidentifiedinFig.7.16byanelementnameoftheforma(i,

j),whereaisthenameofthearrayandiandjaretheindicesthatuniquelyidentifythe

rowandcolumn,respectively,ndicesarezerobased,so

thenamesoftheelementsinrow0allhaveafirstindexof0;thenamesoftheelements

incolumn3allhaveasecondindexof3.

DeclaringandInitializingRectangularArrays

Atwo-dimensionalrectangulararraynumberswithtworowsandtwocolumnscanbe

declaredandinitializedwith

Clickheretoviewcodeimage

Dimnumbers(1,1)AsInteger'numbersina2by2array

numbers(0,0)=1'leftmostelementinrow0

numbers(0,1)=2'rightmostelementinrow0

numbers(1,0)=3'leftmostelementinrow1

numbers(1,1)=4'rightmostelementinrow1

Alternatively,theinitializationcanbewrittenononeline,asshownwithandwithout

localtypeinferencebelow:

Clickheretoviewcodeimage

Dimnumbers={{1,2},{3,4}}

Dimnumbers(,)AsInteger={{1,2},{3,4}}

Intheseconddeclaration,thecommain(,)indicatesthatnumbersisatwo-dimensional

uesaregroupedbyrowinbraces,with1and2initializingnumbers(0,0)

andnumbers(0,1),respectively,and3and4initializingnumbers(1,0)andnumbers(1,

1),pilerdeterminesthenumberofrowsbycountingthenumberof

sub-initializerlists(representedbythesetsofdataincurlybraces)inthemaininitializer

ecompilerdeterminesthenumberofcolumnsineachrowbycountingthe

initializerlists

musthavethesamenumberofelementsforeachrow.

ManipulatingaRectangularArray

TheappinFig.7.17initializesrectangulararrayvaluesandusesnestedFor...Nextloops

totraversethearray(thatis,tomanipulateeveryarrayelement).Thecontentsofthearray

aredisplayedinoutputTextBox.

Clickheretoviewcodeimage

1'Fig.7.17:

2'Initializinganddisplayingarectangulararray.

3PublicClassRectangularArray

4'displaythecontentsofarectangulararray

5PrivateSubRectangularArray_Load(senderAsObject,

6eAsEventArgs)

7

8Dimvalues(,)AsInteger={{1,2,3},{4,5,6}}

9

10'outputelementsofthevaluesarray

11Forrow=erBound(0)

12Forcolumn=erBound(1)

Text(values(row,column)&vbTab)

14Nextcolumn

15

Text(vbCrLf)

17Nextrow

18EndSub'RectangularArray_Load

19EndClass'RectangularArray

lizinganddisplayingarectangulararray.

Theappdeclaresrectangulararrayvalues(line8)andusesaninitializerlistto

determinethenumberofrows,numberofcolumnsandinitialvaluesofthearray’s

berofsublistsdeterminesthe

pilerusesthenumberofelementsinthefirstsublist

sequentsublistsmusthavethe

samenumberofinitializersasthefirstsublist;otherwise,

firstsublistinitializesrow0ofthearraytothevalues1,2and3;thesecondsublist

initializesrow1ofthearraytothevalues4,5and6.

ThenestedFor...Nextstatementsinlines11–17displaytheelementsofrectangular

erFor...Nextstatementtraversestherows;theinnerFor...Next

r...Nextstatementcallsmethod

GetUpperBoundtoobtaintheupperboundofthedimensionittraverses.

GetUpperBoundwiththeargument0(line11)returnsthenumberofrows.

GetUpperBoundwiththeargument1(line12)returnsthenumberofcolumnsineach

row.

udy:MaintainingGradesUsingaRectangularArray

erthefollowing

problemstatement:

desonthese

tructorhasaskedyouto

developanapptokeeptrackofeachstudent’saverageandtheclassaverage.

Theinstructorhasalsoaskedthattherebeachoicetoviewthegradesaseither

gradesshouldbecalculatedaccordingtothe

followinggradingsystem:

Theappshouldallowausertoinputeachstudent’sthreetestgrades,then

computeeachstudent’saverageandtheclassaverageforallgradesenteredso

ldalsodisplaya

gradedistributionchartshowinghowmanyofthenumericgradesfallintothe

ranges0–9,10–19,...90–99and100.

We’llusearectangulararraywith10rowsandthreecolumnstostorethestudentgrades.

Thisappusesmostoftheprogrammingconceptsyou’velearneduptonowinthisbook.

Figure7.19showssampleoutputsfortheGradeReportapp.

a)GradeReportwindowaftertheuserhasenteredthefirststudent’sgradesandis

abouttosubmitthem.

b)GradeReportwindowafterfivestudents’gradeshavebeenentered.

c)GradeReportwindowaftertheuserhasenteredall10students’grades.

d)GradeReportwindowaftertheuserhasenteredall10students’gradesand

clickedtheLetterRadioButtontodisplaylettergrades.

outputsfortheGradeReportapp.

GUIfortheGradeReportApp

app,weintroduce

RadioButtoncontrolstoallowtheusertoselectbetweendisplayinggradesinnumericor

Buttonisasmallwhitecirclethateitherisblankorcontainsa

adioButtonisselected,Buttonis

knownasastatebuttonbecauseitcanbeinonlythe―on‖(True)stateorthe―off‖(False)

’vepreviouslyusedtheCheckBoxstatebuttons(introducedinChapter5).

theGradeReportapp

RadioButtonsaresimilartoCheckBoxes,butRadioButtonsnormallyappearasa

group—rradio

presetbuttons,whichcanselectonlyonestationatatime,RadioButtonsrepresentaset

ofoptionsinwhichonlyoneoptioncanbeselectedatatime—alsoknownasmutually

ult,

separatethemintoseveralgroups,eachgroupmustbeinadifferentcontainer(typicallya

GroupBox).

ARadioButton’sBooleanCheckedpropertyindicateswhethertheRadioButtonis

checked(containsasmalldot)orunchecked(blank).IftheRadioButtonischecked,the

CheckedpropertyreturnsTrue;otherwise,itreturnsFalse.

C

thiseventtoswitchbetweenthenumericgradeandlettergradeviewsinthe

gradesListBox.

GradeReportApp

Overthenextseveralfigureswe’lldiscusstheGradeReportapp’hesize

ofthisapp,we’vesplitthesourcecodeintoseveralsmallfigures.

Figure7.20declaresclassGradeReport’sinstancevariablesandLoadeventhandler.

Therectangulararraygrades(line4)has10rowsand3columnstostorethegradesfor

lestudentCount(line5)keepstrackof

10studentsareprocessed,theappdisables

deReport_Loadeventhandler(lines

8–13)displaysthecolumnheadsinthegradesListBox.

Clickheretoviewcodeimage

1'Fig.7.20:

2'Gradereportusingarectangulararray.

3PublicClassGradeReport

4Dimgrades(9,2)AsInteger'stores10students'gradeson3tests

5DimstudentCountAsInteger=0'numberofstudentsentered

6

7'displayheadingingradeListBox

8PrivateSubGradeReport_Load(senderAsObject,

9eAsEventArgs)

10'headingsrowforgradesListBox

(vbTab&vbTab&"Test1"&vbTab&

12"Test2"&vbTab&"Test3"&vbTab&"Average")

13EndSub

14

eportapp:InstancevariablesandmethodGradeReport_Load.

MethodsubmitButton_Click

Whentheuserentersthreegrades,thenpressestheSubmitButton,methodsubmit-

Button_Click(Fig.7.21)processesthethreegradesanddisplaysthecurrentclass

average

20–22getthethreegradesfromtheTextBoxesandassignthemtotheelementsofthe

25–37buildaStringrepresentingthecurrent

student’28–37loopthroughthecurrentrowofthegrades

arrayandappendeitheralettergradeornumericgrade,basedonwhetherthe

letterRadioButton’,line32callsmethodLetterGrade

ise,line35appendsthe

40callsmethodCalculateStudentAveragetoobtainthecurrent

student’saverageforthethreeexams.

Clickheretoviewcodeimage

15'processonestudent'sgrades

16PrivateSubsubmitButton_Click(senderAsObject,

17eAsEventArgs)

18

19'retrievethestudent'sgrades

20grades(studentCount,0)=32()

21grades(studentCount,1)=32()

22grades(studentCount,2)=32()

23

24'begincreatingStringcontainingthestudent'sgradesandaverage

25DimoutputAsString="Student"&studentCount&vbTab

26

27'appendeachtestgradetotheoutput

28Forcolumn=erBound(1)

29'iftheLetterRadioButtonischecked

d=TrueThen

31'appendlettergradetotheoutput

32output&=vbTab&LetterGrade(grades(studentCount,column))

33Else

34'appendnumbergradetotheoutput

35output&=vbTab&grades(studentCount,column)

36EndIf

37Next

38

39'appendthestudent'stestaveragetotheoutput

40output&=vbTab&CalculateStudentAverage(studentCount)

41

(output)'addoutputtotheListBox

43studentCount+=1'updatenumberofstudentsentered

=CalculateClassAverage()'displayclassaverage

45DisplayBarChart()'displaythecurrentgradedistribution

46

47'cleartheinputTextBoxesandsetfocustofirstTextBox

()

()

()

()

52

53'limitnumberofstudents

54IfstudentCount=erBound(0)+1Then

d=False'disableGroupBox'scontrols

56EndIf

57EndSub'submitButton_Click

58

eportapp:MethodsubmitButton_Click.

43updatesthestudent

44and45callthemethodsCalculateClassAverageandDisplayBarChartto

determinethecurrentclassaverageandtodisplayagradedistributionchartbasedonthe

48–51preparetheuserinterfacetoreceivethe

nextstudent’sgradesbyclearingtheTextBoxesandgivingthefocustothetest1-

y,lines54–

so,line55setstheinputGradeGroupBox’sEnabledpropertytoFalse,whichdisablesall

thecontrolsintheGroupBox,preventingtheuserfromenteringmoregrades.

MethodRadioButton_CheckChanged:HandlingMultipleEventswithOneEventHandler

Atanytime,theusercanselecttheNumericorLetterRadioButtontochangehowthe

eselectedRadioButtonchanges,

methodRadioButton_CheckedChanged(Fig.7.22)example,wehandle

bothRadioButton’is,

doubleclicktheNumericRadioButton,thenrenametheeventhandlerto

RadioButton_,dChangedtothe

Handlesclauseoftheeventhandler(lines62–63).Nowthismethodiscalledwhenthe

case,aslongasatleastone

studenthasbeenprocessed,line67callsmethodDisplayGradestoupdatethe

presentationofthegradesingradesListBox.

Clickheretoviewcodeimage

59'handlesNumericandLetterRadioButtons'CheckChangedevents

60PrivateSubRadioButton_CheckedChanged(senderAsObject,

61eAsEventArgs)_

dChanged,

dChanged

64

65'iftherearegradestodisplay,callDisplayClassGrades

66IfstudentCount>0Then

67DisplayClassGrades()

68EndIf

69EndSub'RadioButton_CheckedChanged

70

eportapp:MethodRadioButton_CheckedChanged.

MethodCalculateStudentAverage

MethodCalculateStudentAverage(Fig.7.23)processesonerowofthegradesarrayto

determinethecorrespondingstudent’hodreturnsaStringcontaining

eitherthelettergradeforthatstudent’saverageorthenumericvalue,dependingon

whethertheletterRadioButton’sCheckedpropertyisTrue.

Clickheretoviewcodeimage

71'calculatesastudent'stestaverage

72FunctionCalculateStudentAverage(rowAsInteger)AsString

73DimgradeTotalAsInteger=0'student'stotalgrade

74

75'sumthegradesforthestudent

76Forcolumn=erBound(1)

77gradeTotal+=grades(row,column)

78Next

79

80DimstudentAverageAsString='outputstring

81

82'calculatethestudent'stestaverage

d=TrueThen

84studentAverage=

85LetterGrade(gradeTotal/(erBound(1)+1))

86Else

87studentAverage=("{0:F}",

88(gradeTotal/(erBound(1)+1)))

89EndIf

90

91ReturnstudentAverage'returnthestudent'saverage

92EndFunction'CalculateStudentAverage

93

eportapp:MethodCalculateStudentAverage.

MethodCalculateClassAverage

MethodCalculateClassAverage(Fig.7.24)processesthegradesarraytodeterminethe

hodreturnsaStringcontaining

eitherthelettergradefortheclassaverageorthenumericvalue,dependingonwhether

theletterRadioButton’sCheckedpropertyisTrue.

Clickheretoviewcodeimage

94'calculatestheclassaverage

95FunctionCalculateClassAverage()AsString

96DimclassTotalAsInteger=0'class'stotalgrade

97

98'loopthroughallrowsthatcurrentlycontaingrades

99Forrow=0TostudentCount-1

100'loopthroughallcolumns

101Forcolumn=erBound(1)

102classTotal+=grades(row,column)'addgradetototal

103Nextcolumn

104Nextrow

105

106DimclassAverageAsString='outputstring

107

108'iftheLetterRadioButtonischecked,returnlettergrade

d=TrueThen

110classAverage=LetterGrade(classTotal/

111(studentCount*(erBound(1)+1)))

112Else'returnnumericgrade

113classAverage=("{0:F}",(classTotal/

114(studentCount*(erBound(1)+1))))

115EndIf

116

117ReturnclassAverage'returntheclassaverage

118EndFunction'CalculateClassAverage

119

eportapp:MethodCalculateClassAverage.

MethodLetterGrade

MethodLetterGrade(Fig.7.25)receivesanumericgradeandreturnsthecorresponding

lettergradeasaString.

Clickheretoviewcodeimage

120'determinesalettergradecorrespondingtoanumericgrade

121FunctionLetterGrade(gradeAsDouble)AsString

122DimoutputAsString'thelettergradetoreturn

123

124'determinethecorrectlettergrade

125SelectCasegrade

126CaseIs>=90

127output="A"

128CaseIs>=80

129output="B"

130CaseIs>=70

131output="C"

132CaseIs>=60

133output="D"

134CaseElse

135output="F"

136EndSelect

137

138Returnoutput'returnthelettergrade

139EndFunction'LetterGrade

140

eportapp:MethodLetterGrade.

MethodDisplayClassGrades

MethodDisplayClassGrades(Fig.7.26)displaysthestudentgradesandaveragesinthe

143clearstheListBox’scurrentcontentsandlines146–147display

150–169processesthegradesarraytodisplayall

thegradesenteredsofar,displayinglettergradesifletterRadioButton’sChecked

172updatestheclassaverageanddisplaystheresultin

averageLabel.

Clickheretoviewcodeimage

141'displaythegradesforallstudentsentered

142SubDisplayClassGrades()

()'cleartheListBox

144

145'addtheheadertotheListBox

(vbTab&vbTab&"Test1"&vbTab&

147"Test2"&vbTab&"Test3"&vbTab&"Average")

148

149'loopthroughalltherows

150Forrow=0TostudentCount-1

151DimoutputAsString="Student"&row&vbTab

152

153'loopthroughallthecolumns

154Forcolumn=erBound(1)

d=TrueThen

156'addlettergradetooutputstring

157output&=vbTab&LetterGrade(grades(row,column))

158Else

159'addnumbergradetooutputstring

160output&=vbTab&(grades(row,column))

161EndIf

162Nextcolumn

163

164'addthestudent'saveragetotheoutput

165output&=vbTab&CalculateStudentAverage(row)

166

167'addtheoutputtotheListBox

(output)

169Nextrow

170

171'updatetheclassaverage

=CalculateClassAverage()

173EndSub'DisplayClassGrades

174

eportapp:MethodDisplayClassGrades.

MethodDisplayBarChart

mple,numeric

achart,longerbarsrepresent

proportionallylargernumericvalues(seeFig.7.18).MethodDisplayBarChart(Fig.7.27)

displaysagraphicalsummaryofthegradedistributionbycreatingabarchartthatshows

howmanynumericgradesfallintoeachoftheranges0–9,10–19,...90–99and100.

Clickheretoviewcodeimage

175'displayabarchartofthegradedistribution

176SubDisplayBarChart()

()'removecurrentitems

178

179'storesfrequencyofgradesineachrangeof10grades

180Dimfrequency(10)AsInteger

181

182'foreachgrade,incrementtheappropriatefrequency

183Forrow=0TostudentCount-1

184Forcolumn=erBound(1)

185frequency(grades(row,column)10)+=1

186Nextcolumn

187Nextrow

188

189'foreachgradefrequency,displaybarofasterisks

190Forcount=erBound(0)

191DimbarAsString'storesthelabelandbar

192

193'createbarlabel("00-09:",...,"90-99:","100:")

194Ifcount=10Then

195bar=("{0,5:D}:",100)

196Else

197bar=("{0,2:D2}-{1,2:D2}:",

198count*10,count*10+9)

199EndIf

200

201'appendbarofasterisks

202Forstars=1Tofrequency(count)

203bar&=("*")

204Next

205

(bar)'displaybar

207Nextcount

208EndSub'DisplayBarChart

209EndClass'GradeReport

eportapp:MethodDisplayBarChart.

Lines180–187summarizethenumberofgradesineachrangeusingtheelementsof

,lines190–207buildaStringcontainingtherange

ofvaluesrepresentedbythecurrentbar(lines194–199)andabarofasterisks

representingthenumberofgradesthatfallintothatrange(lines202–204).Line206then

matStringsinlines195and197use

fimat

specifier{0,5:D}(line195)indicatesthatanintegervaluewillbedisplayedinafieldof

,ifthenumbercontainsfewerthan5characters,

matspecifier{0,2:D2}

(line197)2

forcesthenumbertousetwocharacterpositions—singledigitnumbersareprecededbya

leading0.

nganArraywiththeReDimStatement

Anarray’ssizecannotbechanged,soanewarraymustbecreatedifyouneedtochange

imstatement―resizes‖anarrayatexecutiontime

array’s

7.28demonstratestheReDim

statement.

Clickheretoviewcodeimage

1'Fig.7.28:

2'ResizeanarrayusingtheReDimstatement.

3PublicClassReDimTest

4'demonstrateReDim

5PrivateSubReDimTest_Load(senderAsObject,

6eAsEventArgs)

7

8'createandinitializetwo5-elementarrays

9Dimvalues1()AsInteger={1,2,3,4,5}

10Dimvalues2()AsInteger={1,2,3,4,5}

11

12'displayarraylengthandtheelementsinarray

Text(

14"Theoriginalarrayhas"&&"elements:")

15DisplayArray(values1)

16

17'changethesizeofthearraywithoutthePreservekeyword

18ReDimvalues1(6)

19

20'displaynewarraylengthandtheelementsinarray

Text("Newarray(withoutPreserve)has"&

&"elements:")

23DisplayArray(values1)

24

25'changethesizeofthearraywiththePreservekeyword

26ReDimPreservevalues2(6)

27values2(6)=7'assign7toarrayelement6

28

29'displaynewarraylengthandtheelementsinarray

Text("Newarray(withPreserve)has"&

&"elements:")

32DisplayArray(values2)

33EndSub

34

35'displayarrayelements

36SubDisplayArray(array()AsInteger)

37ForEachnumberInarray

Text(number&"")

39Next

40

Text(vbCrLf)

42EndSub'DisplayArray

43EndClass'ReDimTest

anarrayusingtheReDimstatement.

10createsasecond

13–15displaythesizeandelements

18usesaReDimstatementtochangetheupperboundofvalues1to6,

imstatementcontainskeyword

ReDim,followedbythenameofthearraytobe"resized"andthenewupperboundin

21–put

ofFig.7.28showsthataftertheReDimstatementexecutes,thesizeofvalues1is

changedto7andthevalueofeachelementisreinitializedtothedefaultvalueofthetype

ofthearrayelement(thatis,0forIntegers).Tosavetheoriginaldatastoredinanarray,

26usesPreserve

intheReDimstatementtoindicatethattheexistingarrayelementsaretobepreservedin

ewarrayissmallerthantheoriginal

array,thee

thenewarrayislargerthantheoriginalarray,alltheexistingelementsarepreservedin

thenowlargerarray,andtheextraelementsareinitializedtothedefaultvalueofthetype

mple,afterline26executes,thevalueofvalues2(5)is0.

Line27assignsthevalue7tovalues2(6),sothatthenowlargerarrayvalues2contains

elements1,2,3,4,5,30–32displaythesizeandelementsofvalues2.

-Up

Thischapterbeganourdiscussionofdatastructures,usingarraystostoredatainand

nstratedhowtodeclareanarray,

edhowtopass

ussedhowtousetheForEach...Nextstatementtoiterate

methodSortofclass

ArraytosortanarrayandmethodBinarySearchofclassArraytosearchasortedarray

ainedhowtodeclareandmanipulaterectangular

y,wedemonstratedhowtousetheReDimstatementtodynamicallychange

anarray’extchapter,you’lllearnhowtowritedatatoandreaddatafrom

files.

Summary

Section7.2Arrays

•Anarrayisagroupofvariables(calledelements)containingvaluesthatall

havethesametype.

•Allarraysareobjectsofandhavethemethodsandpropertiesofclass

.

•Torefertoaparticularelementinanarray,specifythenameofthearrayandthe

positionnumberoftheelement.

•Thefirstelementineveryarrayisthezerothelement.

•Thehighestpositionnumberinaarrayisalwas1lessthanthenumberofelements

inthearray.

•Thepositionnumberinparenthesesmoreformallyiscalledanindexandmustbe

anonnegativeintegerorintegerexpression.

•Thenameofanarrayelementcanbeusedontheleftsideofanassignment

statementtoplaceanewvalueintoanarrayelement.

•Everyarray―knows‖itsownlengthviaitsLengthproperty.

Section7.3DeclaringandAllocatingArrays

•Inanarraydeclaration,theparenthesesthatfollowthevariablenameindicatethe

variablerepresentsanarray.

•Arrayscanbedeclaredtocontainelementsofanytype;everyelementofthearray

isofthattype.

•Thenumberinparenthesesinthearraydeclarationrepresentsthearray’supper

boundandhelpsthecompilerallocatememoryforthearray.

•Youcanfollowanarraydeclarationwithanequalsignandaninitializerlistin

braces,{and},tospecifytheinitialvaluesofthearray’piler

determinesthearrayboundsfromthenumberofelementsintheinitializerlist.

•Whenyoudonotprovideaninitializerlist,theelementsinthearrayareinitialized

tothedefaultvalueforthearray’stype—0fornumericprimitivedata-type

variables,FalseforBooleanvariablesandNothingforStringandotherclass

types.

Section7.4InitializingtheValuesinanArray

•ArraymethodGetUpperBoundreturnstheindexofthelastelementinanarray.

ThevaluereturnedbymethodGetUpperBoundisonelessthanthevalueofthe

array’sLengthproperty.

Section7.5SummingtheElementsofanArray

•Often,theelementsofanarrayrepresentaseriesofrelatedvaluesthatareusedin

acalculation.

Section7.6UsingArraystoAnalyzeSurveyResults

•Arrayscanbeusedassetsofcounters.

•Whenanexpressioncontainsnestedparentheses,itsevaluationbeginswiththe

valueintheinnermostsetofparentheses.

•Whenanappisexecuted,arrayelementindicesarecheckedforvalidity—all

i

anattemptismadetouseaninvalidindextoaccessanelement,an

IndexOutOfRangeExceptionexceptionoccurs.

Section7.8CaseStudy:FlagQuiz

•TheComboBoxcontrolpresentsoptionsinadrop-downlistthatopenswhenyou

Boxcombines

featuresofaTextBoxandaListBox.

hoosean

itemfromthislist,thatitemisdisplayedintheComboBox.

•YoumayalsotypeintotheComboBoxcontroltolocateanitem.

•ComboBoxpropertyDropDownStyledeterminestheComboBox’sappearance.

ComboBoxstyle,ifyoupressthekeythatcorrespondstothefirstletterofa

ComboBoxitem,thatitemisselectedanddisplayedintheComboBox.

•PropertyMaxDropDownItemsspecifiesthemaximumnumberofitemsto

calscrollbarisaddedtothedrop-downlisttoallowusers

toscrollthroughtheremainingitems.

•ComboBoxpropertyDataSourcespecifiesthesourceoftheitemsdisplayedin

theComboBox.

•StringmethodReplacereceivestwoarguments—thesubstringthatshouldbe

replacedthroughouttheoriginalStringandthethereplacementsubstring.

Section7.9PassinganArraytoaMethod

•Topassanarrayargumenttoamethod,specifythenameofthearraywithout

usingparentheses.

•Everyarrayobject―knows‖itsownupperbound,sowhenyoupassanarray

objecttoamethod,youdonotneedtopasstheupperboundofthearrayasa

separateargument.

•Foramethodtoreceiveanarraythroughamethodcall,themethod’sparameter

listmustspecifythatanarraywillbereceived.

•Whenyoupassanarraytoamethod,themethodreceivesacopyofthearray’s

referenceandcanchangetheoriginalarray’selementvalues.

•Topassanarrayelementtoamethod,usetheindexednameofthearrayelement

vidualelementcanbepassedbyvalue

orbyreference.

Section7.10ForEach...NextRepetitionStatement

•TheForEach...Nextrepetitionstatementiteratesthroughthevaluesinadata

structure,suchasanarray,withoutusingaloopcounter.

•Whenusedwithone-dimensionalarrays,ForEach...Nextbehaveslikea

For...Nextstatementthatiteratesthroughtherangeofindicesfrom0tothevalue

returnedbyGetUpperBound(0).

•Insteadofacounter,ForEach...Nextusesavariabletorepresentthevalueof

eachelement.

•TheheaderofaForEachrepetitionstatementspecifiesavariableandanarray.

Thetypeofvariableisdeterminedfromthetypeoftheelementsinthearray.

•TheForEachstatementiteratesthroughalltheelementsinthearray,sequentially

assigningeachvaluetothevariablespecifiedintheheader.

Section7.11SortinganArraywithMethodSortofClassArray

•Sortingdataisoneofthemostpopularcomputingapplications.

•ClassArrayprovidesmethodsforcreating,modifying,sortingandsearching

arrays.

•ArraymethodSortsortsanarray’selementsintoascendingorder.

•Tosortanarrayindescendingorder,firstcallmethodSorttosortthearray,then

ewiththearrayasanargumenttoreversetheorderofthe

elementsinthearray.

Section7.12SearchinganArraywithLinearSearch

•Theprocessoflocatingaparticularelementvalueinanarrayiscalledsearching.

•Alinearsearchiteratesthroughalltheelementsofanarray,comparingeach

lementsofthearraybeingsearchedare

unordered,it’sjustaslikelythatthevaluewillbefoundinthefronthalfofthe

arrayasinthebackhalf,soonaveragethemethodwillhavetocomparethe

searchkeywithhalftheelementsofthearray.

•ClassArray’rrayalso

providesmethodssuchasFindandFindAll,whichsearchthearrayforelement(s)

thatmeetcertaincriteria.

Section7.13SearchingaSortedArraywithArrayMethodBinarySearch

•h-speedbinary

searchtechniqueisbetterforsortedarrays.

methodreceivesasortedarrayandasearchkeyandreturnstheindexofthe

searchkey;otherwise,itreturnsanegativenumber.

Section7.14RectangularArrays

•One-dimensionalarraysarearraysthatcontainalistofvalues.

•Multidimensionalarraysrequiretwoormoreindicestoidentifyparticular

elements.

•Two-dimensional(rectangular)arraysareoftenusedtorepresenttablesofvalues

wisthesamesize,andeachcolumnisthe

samesize.

•Toidentifyaparticulartableelement,wespecifytwoindices—byconvention,the

firstidentifiestheelement’srow,thesecondtheelement’scolumn.

•Everyelementinarectangulararrayisidentifiedbyanelementnameoftheform

a(i,j),whereaisthenameofthearrayandiandjaretheindicesthatuniquely

identifytherowandcolumn,respectively,ofeachelementinarraya.

•Arectangulararrayisdeclaredbyplacingtwoboundsseparatedbyacommain

theparenthesesthatfollowthevariablename.

•Ifaninitializerlistisused,thentheparenthesesmustcontainonlythecomma.

Theinitializerlistmusthavesubliststorepresenteachrowandallsublistsmust

pilerdeterminesthenumberof

columnsineachrowbycountingthenumberofinitializervaluesinthe

subinitializerlistforthatrow.

•RectangulararraysareoftenmanipulatedwithnestedFor...Nextloops.

•Forarectangulararray,methodGetUpperBoundwiththeargument0returnsthe

erBoundwiththeargument1returnsthenumberof

columnsineachrow.

Section7.15CaseStudy:MaintainingGradesUsingaRectangularArray

•ARadioButtonisasmallwhitecirclethateitherisblankorcontainsasmalldot.

WhenaRadioButtonisselected,Buttonis

knownasastatebuttonbecauseitcanbeinonlythe―on‖(True)stateorthe―off‖

(False)state.

•RadioButtonsaresimilartoCheckBoxes,butRadioButtonsnormallyappearasa

group—onlyoneRadioButtoninthegroupcanbeselectedatatime—alsoknown

asmutuallyexclusiveoptions.

•ToseparateRadioButtonsintoseveralgroups,eachgroupmustbeinadifferent

container(typicallyaGroupBox).

•ARadioButton’sBooleanCheckedpropertyindicateswhethertheRadioButton

ischecked(containsasmalldot)orunchecked(blank).IftheRadioButtonis

checked,theCheckedpropertyreturnsTrue;otherwise,itreturnsFalse.

•ACheckedChangedeventoccurswhenaRadioButtoniseitherselectedor

deselected.

•mple,

achart,longer

barsrepresentproportionallylargernumericvalues.

Section7.16ResizinganArraywiththeReDimStatement

•TheReDimstatementenablesyoutodynamicallychangeanarray’

―resizes‖anarraybycreatinganewarrayandassigningittothespecified

variable.

•AReDimstatementcontainskeywordReDim,followedbythenameofthearray

tobe―resized‖ueofeach

elementisreinitializedtothedefaultvalueofthetypeofthearrayelement.

•Tosavetheoriginaldatastoredinanarray,followtheReDimkeywordwiththe

ewarrayissmallerthantheoriginalarray,the

e

newarrayislargerthantheoriginalarray,alltheexistingelementsarepreserved

inthenowlargerarray,andtheextraelementsareinitializedtothedefaultvalue

ofthetypeofthearrayelement.

Terminology

array239

arraybounds241

Arrayclass239

binarysearch259

BinarySearchmethodofclassArray261

boundschecking245

Catchblock246

CheckedpropertyoftheRadioButtoncontrol267

CheckedChangedeventoftheRadioButtoncontrol267

columninarectangulararray262

ComboBoxcontrol249

DataSourcepropertyofaComboBox251

DropDownListvalueofpropertyDropDownStyle249

DropDownStylepropertyofComboBox249

elementofanarray239

exception245

exceptionhandling245

fault-tolerantprogram245

ForEach...Nextstatement255

GetUpperBoundmethodofclassArray241

indexofanarray239

initializerlist241

keyvalue259

lengthofanarray240

LengthpropertyofclassArray240

linearsearch259

m-by-narray262

MaxDropDownItemspropertyofComboBoxcontrol249

Messagepropertyofanexception246

multidimensionalarray262

mutuallyexclusiveoptionsandRadioButtons267

one-dimensionalarray262

Preservekeyword275

RadioButtoncontrol266

rectangulararray262

ReDimstatement274

ReplacemethodofclassString252

ReversemethodofclassArray259

rowinarectangulararray262

searchkey259

searching259

SelectedIndexpropertyofaComboBox252

sorting257

SortmethodofclassArray257

tableofvalues262

two-dimensionalarray262

throwanexception246

Tryblock246

Trystatement246

upperbound239

zerothelement239

Self-ReviewExercises

7.1Answereachofthefollowingquestions:

a)Thenumberthatreferstoaparticularelementofanarrayiscalledits

_________.

darrayname

b)Theindexedarraynameofone-dimensionalarrayunits’selement2is

_________.

{2}

(2)

[0,2]

[2]

c)Anarray’slengthis_________.

ethanthearray’slastindex

sthanthearray’slastindex

easthearray’slastindex

edbymethodGetUpperBound

d)Property_________specifiesthesourceofthedatadisplayedina

ComboBox.

ata

st

urce

e)ComboBoxproperty_________is0whenthefirstComboBoxitemis

selected.

edIndex

edValue

edNumber

f)Theprocessoforderingtheelementsofanarrayiscalled_________thearray.

ting

g

ing

lizing

g)WhichofthefollowingsortsarrayaverageRainfall?

(averageRainfall).Sort()

(averageRainfall)

(averageRainfall)

(averageRainfall)

h)Arraysthatusetwoindicesarereferredtoas_________arrays.

-dimensional

-dimensional

-dimensional

i)Theexpression_________createsanIntegerarrayoftworowsandfive

columns.

(2,5)AsInteger

(1,5)AsInteger

(1,4)AsInteger

(2,4)AsInteger

j)The_________eventisraisedwhenaRadioButtoniseitherselectedor

deselected.

dChanged

d

edChanged

theabove

k)WhenoneRadioButtoninacontainerisselected,_________.

canbeselectedatthesametime

errorwilloccur

erswillbedeselected

1and2

l)Typically,_________statementsareusedtoiterateovereachelementina

two-dimensionalarray.

e...Loop

For...Next

...LoopUntil

Do...LoopWhile

e,explainwhy.

a)Anarraycanstoremanydifferenttypesofvalues.

b)AnarrayindexnormallyshouldbeoftypeDouble.

c)MethodGetUpperBoundreturnsthehighestnumberedindexinanarray.

d)Todeterminethenumberofelementsinanarray,usetheNumberOfElements

property.

e)Thelinearsearchworkswellforunsortedarrays.

AnswerstoSelf-ReviewExercises

7.1a)4.b)2.c)1.d)4.e)1.f)2.g)4.h)2.i)3.j)1.k)3.l)2.

7.2a)ycanstoreonlyvaluesofthesametype.b)y

indexmustbeanonnegativeintegerorintegerexpression.c)True.d)

determinethenumberofelementsinanarray,wecanusetheLengthproperty.e)

True.

QuickQuiz

7.3Answereachofthefollowingquestions:

a)Arrayscanbedeclaredtoholdvaluesof_________.

uble

teger

ring

atype

b)Anarray’selementsarerelatedbythefactthattheyhavethesamenameand

_________.

ntvalue

c)Method_________returnsanarray’shighestindex.

erBound

erLimit

hestIndex

erIndex

d)Thefirstelementineveryarrayisthe_________.

element

ofthearray

stvalueinthearray

e)Theinitializerlistcan_________.

todeterminethesizeofthearray

nacomma-separatedlistofinitialvaluesforthearrayelements

y

heabove

f)Whichmethodcallsortsarraywordsinascendingorder?

(words)

ray()

(words,1)

(words)

g)TheComboBoxcontrolcombinesaTextBoxcontrolwitha_________

control.

mePicker

x

cUpDown

h)Property_________containsthesizeofanarray.

ts

ize

i)Whendeclaringanarray,a(n)_________isrequiredinsideparenthesesin

ordertoindicatethatthearrayistwo-dimensional.

sk

ophe

j)Ina_________arrayeachrowcontainsthesamenumberofcolumns.

gular

r

heabove

k)Inanm-by-narray,themstandsfor_________.

berofcolumnsinthearray

alnumberofarrayelements

berofrowsinthearray

berofelementsineachrow

l)WhichofthefollowingcreatesanIntegerarrayoffiverowsandthreecolumns?

ues(5,3)AsInteger

ues(4,2)AsInteger

ues(4,3)AsInteger

ues(5,2)AsInteger

m)Usea_________togroupRadioButtonsonaForm.

oxcontrol

oxcontrol

xcontrol

theabove

n)The_________propertyissettoTruewhenaRadioButtonisselected.

ed

d

o)Two-dimensionalarraysareoftenusedtorepresent_________.

art

ces

p)WhichofthefollowingstatementscreatesIntegerarrayvalueswiththree

rowsandthreecolumns?

ay()()AsInteger={{1,2,3},{4,5,6},{7,8,9}}

ay()AsInteger={{1,2,3},{4,5,6},{7,8,9}}

ay(,)AsInteger={{1,2,3},{4,5,6},{7,8,9}}

heabove

Exercises

7.4Writestatementstoaccomplisheachofthefollowingtasks:

a)Displaythevalueofelement6ofarraynumbers.

b)UsingaFor...Nextstatement,assignthevalue8toeachofthefiveelements

ofone-dimensionalIntegerarrayvalues.

c)Totalthe100elementsoffloating-pointarrayresults.

d)Copy11-elementarraysourceintothefirstportionof34-elementarray

sourceCopy.

e)Determinethesmallestandlargestvaluesin99-elementfloating-pointarray

data.

7.5(SalarySurveyApp)Useaone-dimensionalarraytosolvethefollowing

problem:

salespeoplereceive$200perweek,plus9%oftheirgrosssalesforthatweek.

Forexample,asalespersonwhogrosses$5,000insalesinaweekreceives$200

plus9%of$5,000,atotalof$napp(usinganarrayofcounters)that

determineshowmanyofthesalespeopleearnedsalariesineachofthefollowing

ranges(assumingthateachsalesperson’ssalaryistruncatedtoaninteger

amount):$200–299,$300–399,$400–499,$500–599,$600–699,$700–799,

$800–899,$900–999andover$999.

rclicks

theCalculateButtontocalculatethesalesperson’euserisdone

enteringthisinformation,clickingtheShowTotalsButtondisplayshowmanyof

thesalespeopleearnedsalariesineachoftheaboveranges.

7.6(CafeteriaSurveyApp)Twentystudentswereaskedtorate,onascalefrom1to

10,thequalityofthefoodinthestudentcafeteria,with1being―awful‖and10

being―excellent.‖

ythefrequenciesasa

barchartinaListBox.

7.7(WhatDoesThisCodeDo?)Thisfunctiondeclaresnumbersasitsparameter.

Whatdoesitreturn?

Clickheretoviewcodeimage

1FunctionMystery(numbers()AsInteger)AsInteger()

2DimlengthAsInteger=-1

3DimtempArray(length)AsInteger

4

5ForiAsInteger=lengthTo0Step-1

6tempArray(length-i)=numbers(i)

7Next

8

9ReturntempArray

10EndFunction'Mystery

7.8(What’sWrongwithThisCode?)ThecodethatfollowsusesaFor...Nextloop

eerror(s)inthefollowingcode:

Clickheretoviewcodeimage

1SubSumArray()

2DimsumAsInteger

3Dimnumbers()AsInteger={1,2,3,4,5,6,7,8}

4

5ForcounterAsInteger=

6sum+=numbers(counter)

7Next

8EndSub'SumArray

7.9(RoadSignTestApp)Writeanappthatteststheuser’sknowledgeofroadsigns.

Yourappshoulddisplayarandomsignimageandasktheusertoselectthesign

namefromaComboBox(similartotheFlagQuizapp).Youcanfindthe

imagesintheImagesfolderwiththischapter’sexamples.

7.10(EnhancedCafeteriaSurveyApp)Aschoolcafeteriaisgivinganelectronic

anappthatusesa

shoulddisplayfourfood

eLikeandDislikeRadioButtonstoallow

r

selectsanitemfromtheComboBox,clickstheappropriateRadioButtonand

yareportthat’supdatedas

ctangularIntegerarraynamed

votes,w

umnsstorethenumberof

―like‖and―dislike‖votes,respectively.

7.11(WhatDoesThisCodeDo?)Whatisreturnedbythefollowingcode?Assume

thatGetStockPricesisaFunctionthatreturnsa2-by-31array,withthefirstrow

containingthestockpriceatthebeginningofthedayandthelastrowcontaining

thestockpriceattheendoftheday,foreachdayofthemonth.

Clickheretoviewcodeimage

1FunctionMystery()AsInteger()

2Dimprices(1,31)AsInteger

3

4prices=GetStockPrices()

5

6Dimresult(30)AsInteger

7

8ForiAsInteger=0To30

9result(i)=prices(1,i)-prices(0,i)

10Next

11

12Returnresult

13EndFunction'Mystery

7.12(What’sWrongwithThisCode?)Findtheerror(s)

TwoDArraysprocedureshouldcreateatwo-dimensionalarrayandinitializeall

itsvaluestoone.

Clickheretoviewcodeimage

1SubTwoDArrays()

2Dimarray(3,3)AsInteger

3

4'assign1toallcellvalues

5ForiAsInteger=0To3

6array(i,i)=1

7Next

8EndSub'TwoDArrays

7.13(DuplicateElimination)Useaone-dimensionalarraytosolvethefollowing

problem:Readin20numbers,eachofwhichisbetween10and100,inclusive.

Aseachnumberisread,displayitinnumbersEnteredListBoxand,ifit’snota

duplicateofanumberalreadyread,e

forthe―worstcase‖(inwhichall20numbersaredifferent).Usethesmallest

possiblearraytosolvethisproblem.

7.14(SortinginAscendingandDescendingOrder)Modifythesortingexampleof

Fig.7.12sothatitdisplaysthe―Originalvalues,‖―Valuessortedinascending

order‖and―Valuessortedindescendingorder‖;yourappshoulddisplayinthe

lasttwocolumnsthevaluessortedinascendinganddescendingorder,

respectively.

7.15(Telephone-NumberWordGenerator)Standardtelephonekeypadscontainthe

berstwothroughnineeachhavethreeletters

associatedwiththem(Fig.7.29).Manypeoplefinditdifficulttomemorize

phonenumbers,sotheyusethecorrespondencebetweendigitsandlettersto

mple,

apersonwhosetelephonenumberis686-2377mightusethecorrespondence

indicatedinFig.7.29todeveloptheseven-letterword―NUMBERS.‖Every

seven-letterwordcorrespondstoexactlyoneseven-digittelephonenumber.A

restaurantwishingtoincreaseitstakeoutbusinesscouldsurelydosowiththe

number825-3688(thatis,―TAKEOUT‖).

onekeypaddigitsandletters.

Everyseven-letterphonenumbercorrespondstomanydifferentseven-letter

unately,mostoftheserepresentunrecognizable

’spossible,however,thattheownerofabarbershop

wouldbepleasedtoknowthattheshop’stelephonenumber,424-7288,

correspondsto―HAIRCUT.‖Aveterinarianwiththephonenumber738-2273

wouldbepleasedtoknowthatthenumbercorrespondstotheletters

―PETCARE.‖Anautomotivedealershipwouldbepleasedtoknowthatthe

dealershipnumber,639-2277,correspondsto―NEW-CARS.‖

Writeanappthatallowstheusertoenteraseven-digitnumberinaTextBox,

anddisplayseverypossibleseven-letterwordcombinationcorrespondingtothat

numberinamultiplelinescrollableTextBoxwhentheuserclickstheGenerate

re2,187(37)honenumbers

withthedigits0and1.

7.16(AirlineReservationsSystem)Asmallairlinehasjustpurchasedacomputerfor

’vebeenaskedtodevelopthenew

towriteanapptoassignseatsoneachflightoftheairline’s

onlyplane(capacity:10seats).

YourappshoulddisplayRadioButtonsthatallowtheusertochooseFirst

serselectsFirstClass,yourappshouldassignaseat

inthefirst-classsection(seats1–5).IftheusertypesEconomy,yourappshould

assignaseatintheeconomysection(seats6–10).Yourappshouldthendisplay

aboardingpassindicatingtheperson’sseatnumberandwhetherit’sinthefirst-

classoreconomysectionoftheplane.

Useaone-dimensionalarrayoftypeBooleantorepresenttheplane’sseating

elementsofthearrayareinitiallyFalsetoindicatethattheseats

seatisassigned,setthecorrespondingelementsofthearray

toTruetoindicatethattheseatisnolongeravailable.

theeconomysectionisfull,yourappshouldaskthepersonifit’sacceptableto

beplacedinthefirst-classsection(andviceversa).Ifyes,maketheappropriate

,displaythemessage"Nextflightleavesin3hours."

MakingaDifferenceExercise

7.17(Polling)TheInternetandthewebareenablingmorepeopletonetwork,joina

cause,voiceopinions,sidentialcandidatesin2008usedthe

Internetintensivelytogetouttheirmessagesandraisemoneyfortheir

exercise,you’llwriteasimplepollingappthatallowsusersto

ratefivesocial-consciousnessissuesfrom1(leastimportant)to10(most

important).Pickfivecausesthatareimportanttoyou(forexample,political

issues,globalenvironmentalissues).Useaone-dimensionalarraytopics(oftype

String)arizethesurveyresponses,usea5-row,

10-columntwo-dimensionalarrayresponses(oftypeInteger),eachrow

eappruns,itshouldask

urfriendsandfamilyrespondtothesurvey.

Thenhavetheappdisplayasummaryoftheresults,including:

a)Atabularreportwiththefivetopicsdowntheleftsideandthe10ratings

acrossthetop,listingineachcolumnthenumberofratingsreceivedforeach

topic.

b)Totherightofeachrow,showtheaverageoftheratingsforthatissue.

c)Whichissuereceivedthehighestpointtotal?Displayboththeissueandthe

pointtotal.

d)Whichissuereceivedthelowestpointtotal?Displayboththeissueandthe

pointtotal.

更多推荐

visual basic下载