Sei sulla pagina 1di 7

Compilingaprogram?

Whenyouwriteprograms,youwriteyoursourcecodesusingaprogramminglanguagewhichis closetoalanguagehumanscanunderstand.Youwilluseconstructslikeif,elseandwhile. However,theseinstructionscannotbedirectlyunderstoodbythecomputer(thelatterunderstands only0sand1s).Sowhatyouneedtodoiscompileyourprogramtoconvertyourinstructionsinto machineinstructionsyourcomputerunderstands. Compilation:Processofconvertinghumanreadablecodestomachinereadablecodes. Question:Howisaninterpreterdifferentfromacompiler?

Reasonstopayattentiontowhatyouwriteinyourprograms:
Canyoureadthis? THEPAOMNNEHALPWEOROFTHEHMUANMNID
Aoccdrnig to rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in What oredr the ltteers in a wrod are, the olny iprmoatnt tihng is taht the frist and lsat ltteers are in the rghit pclae. The rset can be a taotl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a wlohe. Amzanig huh?

Youprobablyread: THEPHENOMENALPOWEROFTHEHUMANMIND
According to research at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letters are in the right place. The rest can be a total mess and you can still read it without a problem. This is because the human mind does not read every letter by itself, but the word as a whole. Amazing huh?

Similarly,whenreadingsometext,youmayfigureoutthataparticularsentenceisa questionevenintheabsenceofthe?symbol. o Why.Gotmypoint,right? CompilershoweverdoNOThavethesamepowerashumanbeingstoreadpoorlywritten words(asitstandstoday),forexample,omitting;attheendofastatementinJAVAyields anerror SowheneverthereisawordtheydoNOTunderstand,theysimplydoNOThandlethese words Whenyouwriteprograms,ifthereareanywordsthecompilerdoesNOTunderstand,you getanerror. Sopaycarefulattentiontodetailsandallsyntaxruleswhenwritingprograms.

TipsforavoidingmakingsyntacticerrorsinJAVA
ThefollowingnotesgivesomeoftherulesforwritingJAVAcodesandhintsonhowtomakesure weabidebythoserules: Any{shouldhaveitscorresponding}. o Wheneveryouwritea{,beforewritinganythingelse,writethecorresponding}and indentittotheproperlevel. o Althoughyourcompilermayacceptsomecodes,semantically,youmaybewriting thewrongcode. Any/*shouldhaveitscorresponding*/. o Wheneveryouwritea/*,beforewritinganythingelse,writethecorresponding*/at thestartofanewline). o Otherwise,youmaymessupasyourcompilertreatsallthatfollowsthe/*as commentandifdowntheroad,youhaveinsertedanothercomment,theendofyour secondcommentwillbetreatedastheclosingcommentsymbol
/* comments1 statements /*comments2 */

All'statements'abovewillbetreatedascomments o Alongthesameline,commentscannotbenestedwithineachother Any(shouldhaveitscorresponding) Allstatementsneedtoendwitha; o exceptforconditionalstatements JAVAisacasesensitivelanguage o Keywordsarealsocasesensitive(ifandIFaredifferenttoyourcompiler) o variablesyoudeclarearealsocasesensitive. e.gheight,Height,hEight,...HEIGHTareallconsidereddifferentsymbols inJAVA CommonMistakesbeginnersandsometimessemipro'smake: Using=insteadof==andviceversa Typingandinadvertantly,pressingtheCapsLockkey,andhavingallstatements beinguppercaseJAVAiscasesensitive,remember. Invertingtheorderofsomecharacters(writingmianinsteadofmain).

Good programming styles [1]:


WritethecommentsfirstStartyourprogramsandprocedures/functionsbywritingafew sentencesexplainingwhattheyaresupposedtodo.IfyouCANNOTwritethesecomments, youprobablydoNOTunderstandwhattheprogramdoes.Itismucheasiertodebug comments,thanprograms,andtheadditionaltypingisworththeeffort. DocumentvariablesWriteaonelinecommentforeachvariablesoyouknowitspurpose. UsesymbolicConstantsDeclareconstantsatthetopofyourprogramandusethemas appropriate Usesubroutines/functionstoavoidredundantcode MakedebuggingstatementsmeaningfulDonotsimplyprintthevariable

Some useful tips to minimize errors:


Saveyourfilesinappropriatedirectories.(Createfolderswithmeaningfulnamestosave yourfiles) Namingconventions('standards'thatmakeyourprogramseasiertoreadandmaintain) o Filesandprograms Givemeaningfulnamestoyourprogramsandfiles(ifaprogramme calculatesaproduct,itmightbeagoodideatocallitproduct.javainsteadof yourname.java(Otherwise,youmightbehavingprogramsnamed yourname.java,yourname1.javayournamen.javaovertime.Thismay lookniceandcute,butisREALLYBADpractice) o Variables Allvariablesshouldbeproperlynamednamesshouldbemeaningful (althoughthenameofyourvariablesdoesnotmakeadifferencetoyour compiler,theydomakeadifferencetoYOUandotherswhoneedtoread, understandandmaintainyourprogram.Forexample,ifyouwanttorepresent theheightofaperson,heightmightbeabetternamethanh. Allvariableswillbelowercase(althoughthereisnothingwrongforyour compilerifyoumixcasesfordifferentvariables,itbecomesmoredifficult forYOUtoreadandunderstandcodes) Allvariablesthatconsistofmorethanonewordshouldbeseparatedbya_, e.g.total_amount,employee_name o Functions Functionswillusuallyconsistoftwoormorewords,averbfollowedbya noun(s).Wewillwritethefirstwordinlowercasewhilesubsequentwords willbeintitlecase,e.g.computeTotal,getName,getPaymentAmount o Constants Constantsshouldberepresentedusinguppercasee.g.MAXCOUNT o Classes Classesshouldbegivenmeaningfulnames,eachwordfromthenameofthe classbeingintitlecase,e.gEmployee,SalariedEmployee,

Note:Theabovenamingconventionisonewechooseforthismodule.Youmayfindother conventionsthatwillbeusedatyourfutureworkplace,forexample,precedinganinteger variablewithani,astringwithans,afloatwithanfetc. Indentation o Makeslogicclear(althoughyourcompilerdoesnotneedindentingtounderstand yourcode) Modularizeyourprograms o Allowsyoutowritecodesthatcanbeusedmorethanonce Allowsyoutowriteprogramsfasterandmakelesserrors Moreonthislater(whenwetalkaboutfunctions) Comments o CommentsshouldcontainProgramname,author,datewritten,purpose,version o Althoughforsmallprograms,itmayseemfutiletowritetheabovecomments,get

intothehabitofwritingthemsoyouincludethemwhenwritingbigprograms. o Commentanyblocksthatyoufeelaretricky(althoughthecodemakessenseatthe timeyouwriteit,imaginecomingbacktoitafter6monthsandtryingtofigureout whatyouwrote(figuringout10,25linesofcodesiseasy,imagineyourselffiguring 1000LOC,10000LOCormore)worse,imaginesomeoneelsewrotesomepiece ofcodewithnocomments,andYOUhavetomaintainit6monthslater(poorYOU). SodoNOTdotootherswhatyouwouldnotwantotherstodotoyou. Haveatemplatethatcontainsthemainstatementsofaprogram o MostprogramsyouwriteinJAVAwillcontainthefollowingmajorcomponents.


/* */ import directives public class Classname { code for attributes code for constructors code for methods public static void main(String argsv[]) { declarations statements } } Comments

Forexample,mostofyourprograms(forthetimebeing)willhavethefollowingform:
/* *************************************************** Purpose: Author: Date: Version: *************************************************** */ import java.util.*; import java.util.Scanner; public class Classname { public static void main(String[] args){ } }

o Youmaywanttosavetheaboveblockasatemplate.Eachtimeyouneedtowritea newprogram,youopenthetemplate,SAVEASanewfile,andaddinyourother codes.Theadvantageisyoudonotneedtokeyinthese,andhencecanfocusonthe majorpartsofyourprogram. o IfyouuseanIDE(EclipseforExample),stubsareusuallycreatedforyouandyou

onlyneedtoaddinyourfunctionality.UsefacilitiesofferedbyyourIDEtomake theprogrammingtaskfaster,forexample,usetherefactoringfacilityofEclipseto renameallinstancesofavariableinyourcodes(fasterandlesserrorprone)

Using the debugger


IDEsusuallyofferadebuggingtoolthatcanbeusedtotraceyourprograms.Debuggersoffer advancedtracetablesintheformofimmediatewindows,addingbreakpointsetc.Makeuseofthe debuggerprovidedbyyourIDEtotraceyourprogramswhenyoudonotgettheexpectedresults. Note:Thedebuggerwillnotbeofanyuseifyouhavesyntaxerrorsinyourprogram,inwhichcase theprogramwillsimplynotcompile.

Other tips for Solving a problem [2]:


ReadtheproblemcarefullyReadeachlineoftheproblemstatementcarefully.Skimthe passagefirst,sincemuchofthedescriptionmaybebackground/historythatdoesnotimpact thesolution. Don'tassumeReadingandunderstandingspecificationsisanimportantpartof programming.Specificationsoftenleaveunspecifiedtrapstofallin.Justbecausesome examplesexhibitsomenicepropertydoesnotmeanthatallthedatawill.Beonthelookout forunspecifiedinputs,unboundedinputnumbers,negativenumbers. Onceyouknowtheproblem,choosetheappropriatedatastructureDonotmakethe problemmorecomplicatedthannecessary.Keepsimplejobssimple.

Testing and debugging [3]:


Testgiveninputifavailable Testincorrectinputiftheproblemspecifiesyourprogramshouldtakesomeactionon illegalinputs,besuretotestforsuchproblematicinstances. TestboundaryconditionsManybugsareduetooffbyoneerrorstestyourcodefor conditionsasemptyinput,oneitem,twoitems...andvalueswhicharezero Testinstanceswhereyouknowthecorrectanswer Testbigexampleswhereyoudonotknowthecorrectanswer Inspectyourcodesbugstendtoinfestcodethatistoouglytoreadortoocleverto understand MakeyourPrintstatementsmeaningful Makesureyourbugsarereallybugsifyouwroteacommandtellingthecomputerto outputnothing,donotexpectittodootherwise

ThetablebelowshowssomeofthesymbolsavailableinC++. Symbol Description // LineComment /* */ { Beginningofacomment Endofacomment Beginningofablockofstatements Comments Usedwheneverweneedtoinsertaone linecomment Usedtoenclosecommentswithinour program Usedtogroupabunchofstatements

} * / = == + ()

Endofablockofstatements Multiplicationoperator Divisionoperator Assignment Testforequality Addition Subtraction Usedinarithmeticoperationsfor precedence Usedwithif,whileconditions

together Becarefultoavoiddivisionbyzero Usedtoassignsomevaluetoavariable Usedtocomparetwovalues

Why is the above important for you?


Wewanttoencourageyoutoadoptgoodprogrammingpracticesrightfromthebeginning Adoptinggoodstyleswillallowyoutodebugyourprogramseasily Althoughitmaynotappearrewardingtousetheabovetechniquesforsmallprograms,you mustadheretothemsothatyouhavethepracticewhenwritinglargerprograms. YouwillbepenalisedifyoudoNOTadheretotheabovetechniques

Loop Common mistakes:


Example1:Initializationwithintheloopwheninitializationshouldbeoutsideloop. Whenavariableisinitialisedorassignedavaluewithinaloop,eachpassthoughtheloopgivesthe variablethesamevalueagain. Forexample,ifyouwrite
do{ System.out.println(Please enter character); j=0; arr1[j]=sc.nextInt(); j++; System.out.println(\nDo you want to continue y/n?); prompt = sc.next(); }while(prompt.equals(y))

Althoughtheintentherewastohavecharactersindifferentpositionsinthearray,arr1,eachvalue isreadintoposition0ofarr1. Example 2: Having redundant break statement

Considerthefollowingcodes:
while(ans=='y') { System.out.println("enter number " +counter+1); arr[counter]=sc.nextInt(); counter++; System.out.println("Do you want to continue y/n? \n"); ans=sc.next(); if (!ans.equals(y)) break; }//end while

Considertheifstatementabove,whichcheckswhethertheuserdidnotenteryandbreaksfrom theloop.Intheabovecase,theifstatementisredundantastheloopwouldhaveterminatedanyway sincetheifblockisthelastblock.. [1]StevenSkiena,MiguelRevillaProgrammingChallenges,Springer,p9 [2]StevenSkiena,MiguelRevillaProgrammingChallenges,Springer,p35 [3]StevenSkiena,MiguelRevillaProgrammingChallenges,Springer,p39

AnwarRChutooandAnujaMeetooAppavoo ComputerScienceandEngineering UniversityofMauritius

Potrebbero piacerti anche