資源描述:
《arrays - cs division - home陣列- cs分回家》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在應用文檔-天天文庫。
1、ArraysWhatarethey?Anarrayisadatastructurethatholdsanumberofrelatedvariables.Thus,anarrayhasasizewhichisthenumberofvariablesitcanstore.Allofthesevariablesmustbeofthesametype.(Inessencedeclaringanarrayallowsyoutousemanyvariablesofthesametypewithoutexplicitl
2、ydeclaringallofthem.)Youcanpictureanarraylikebelow:0123456789Eachcellofthearraycanholdonedataitem.Furthermore,eachcellhasitsownindex,todistinguishitfromtherestofthecells.InJava,thesecellsarealwaysnumberedfrom0tothesizeofthearrayminusone.Thearrayaboveisind
3、exedfrom0-9andhassize10,sinceitcanhold10elements.Hereisthegenericsyntaxforanarraydeclaration:type[];Here'sanexample:int[]numbers;Theabovelineofcodewilldeclareanarraycallednumbers,whichwillholdintegervalues.Itssizeisstillundefinedatthispoint.Sinc
4、eanarrayisn'taprimitive,technically,numbersisjustareference.Atthecurrenttime,noSPACEinthecomputer'smemoryhasbeenallocatedtostoreasetofintegers.Thenextstepistoallocatethisspace.Inordertodothis,weneedtoknowhowmuchspacewewanttoallocate.Ifwewantedtoallocatesp
5、acefor10variables,wewoulddothefollowing:numbers=newint[10];Oncewe'vedonethis,thepicturelookslikethefollowing:---numbers
6、v0123456789Torefertoavariableinasinglecellorelementofanarray,youusethenameofthearray,followedbyabracket,theindexyouwanttoaccess,andthen
7、anotherbracket.Thus,numbers[0]=3;wouldsettheintvariableinthe0indexofthenumbersarrayto3.---numbers
8、v01234567893AsampleprogramThefollowingprogramwillreadinfivetestscoresandthenprinttheseoutinreverseorder:publicstaticvoidmain(String[]args){Scannerstdin=newSc
9、anner(System.in);intindex;int[]test_scores=newint[5];//Readinscoresintothearray.System.out.println("Pleaseenter5testscores.");for(index=0;index<5;index++)test_scores[index]=stdin.nextInt();//Printthemoutbygoingthroughthearrayinbackwards.printf("Herearethe
10、scoresinreverseorder:");for(index=4;index>=0;index--)System.out.print(test_scores[index]+"");System.out.println();}Commonmistakesmadewitharrays1.OutofBoundserror:Thisiswhenyouindexintoanarraywithaninvalidindex.Forex