Sunteți pe pagina 1din 14

07/01/2015 Modules:PrintModule

Lesson1:Programmingwithdatatypesandoperators
Lesson1:Programmingwithdatatypesandoperators

Lesson1:Programmingwithdatatypesandoperators

Objectives
Attheendofthislessonyouwillbeableto...

FortheAndroidapplication:

selectaspecificlayoutforourapplication

addanimagetothelayout

addaTextViewformwidget

addaButtonwidget

ForJavacoding:

identifythebasicguidelinesforaJavaprogram

applytheguidelinesforvariablenamesinaJavaprogram

createablockofcode

recogniseJavakeywords

usesimpletypesinJavacode

specifyliteralsforsimpletypesandforstrings

demonstratetwoormorewaystoinitialisevariables

describethescoperulesofamethod

understandtypeconversioninexpressions

applycastinginJavacode

usethearithmeticoperators

usetherelationalandlogicaloperators

usetheassignmentoperator

Purpose

Whenyouwanttobuysomethinginaforeigncountry,youtypicallyconvertthevalueoftheitemfromtheforeigncurrencytoyourowncurrencytodecideifthecostoftheitemisworthyourmoney.Thissametyp
avalueconversion.

Sometimeswhenyouareaskedtoenteryourphonenumberintoafield,youenteritwithdashesorspaces.Iftheprogramisexpectingjustnumericdata,theprogramwouldneedtoconvertthedata.

Understandingdatatypesandoperatorswillhelpyoutosolvethesetypesofscenarios.

Anotherimportantprogrammingconceptishowtousethearithmetic,logic,andrelationaloperatorseffectively.Accuratecalculations,anddeterminingthepathofprogramexecutionwhenusinglogicandrelatio
fromonecurrencytypetoanotheristobeperformedcorrectly,thearithmeticcalculationswillneedtobeimplementedinthecorrectsequenceandusingtheexactlogicorder.

Similarly,calculatingthetrajectoryofamissileinagamerequiresaccuracyandpreciselogic.Youllexaminealloftheseconceptsinthislesson.

Android:AddingWidgetstotheLayout

Android:AddingWidgetstotheLayout


OpenEclipse
Closeallotherapplicationsthatarestillopen.
CreateaNewAndroidApplicationProject.Saveitas:Lesson1.
Acceptallthedefaultoptions.
Removethe"HelloWorld!"textfromthelayout.

Activity:AddingTextViewwidgets

Fromthe[RecourseChooser]Palette,choose"FirstnameLastname"fromthe[TextFields].

Dragitontothelayout.

Inthe[Properties]add"text"tobedisplayedonthelayout:"Enterfirstname"
NoticetheIdforthetextfield:editText1

Repeatthisandaddasecondfield.Add"text"tobedisplayedas"Enterthesecondname"
NoticetheIdforthetextfield:editText2

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 1/14
07/01/2015 Modules:PrintModule

Activity

AddingFormWidgets

Fromthe[RecourseChooser]Palette,choose"Button"fromthe[FormWidgets].Dragitontothelayout.

Changethe[Text]to"PressMe"

NoticetheIdforthisbutton:button1

AddingafinalTextViewwidget

AddingaTextViewwidgetwherewewilldisplayresults.

Removethetext(TextView)fromthewidget.

NoticetheIdfortheTextViewwidget:textView1

Testyourapplication:

AlwaysSaveandTesttheapplication.

Ifthereareanyerror,resolveitandtestitagain.IfyoubattlewiththeEclipsesimulator,referbacktotheslidewhereweillustratetheuseofBlueStackasanemulator.

(IpreferusingBlueStacktoEclipse'semulator)

YoucanalwayslaunchtheapplicationdirectlyfromEclipse.

YouwillfindLesson1.apkunderthebinfolder.Doubleclicktolaunchit.TheapplicationwillopenineitherEclipse'sorBlueStack's,dependingontheonethatyouhavedecidedtouse.

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 2/14
07/01/2015 Modules:PrintModule

Programmingwithdatatypesandoperators

Programmingwithdatatypesandoperators

IntroductiontoJava

IntroductiontoJava

Objectives
IntroductiontoJava:Programmingwithdatatypesandoperators

Thusfar,wehavecreatedonescreenapplication,calledLesson1.Butyouwillagreewithmethatitisn'treallyveryfunctional.

Weneedtoaddsomeflesh(orprogramming)toit.

ForthepurposeofthislessonwearegoingtodosimpleprogrammingusingdatatypesandoperatorsinJava.

WearegoingtoinvestigateandapplythefollowinginJavacode:

discussandunderstandthedifferentprogrammingdatatypes

howtodeclarevariablesanduseliterals

therulesforchoosingvariablenames

thescopeofavariable

thedifferentarithmeticoperators

theprocesstoapplyconversions

howtoconvertdatatypes

wheretofindtheJavaAPIandMathclass

basicStringoperations

relationalandlogicoperators

Javaprogrammingtypes

JavaProgrammingTypes

InJava,datatypesareusedtodefinethekindofdatathatcanbestoredinavariable.Theyensurethatonlycorrectdataisstored.

Javademandsthatallvariableshaveadatatype.Ifweattempttostoreincorrectdata,theprogramwillnotcompile.

Generally,datatypesareeitherdeclaredorinferred.TheJavalanguageonlyallowsprogramstoexecuteiftheyadhereto
typeconstraints.Javachecksifanexpressionordatahasanincorrecttypeandflagsitasanerroratcompiletime.
Inmoreadvancedprograms,Javaalsoallowstheprogrammertodeclarevariablesusingdatatypesthatthey
themselveshavecreated.

Javahaseightprimitivedatatypesthatareusedtostoredataduringaprogram'soperation.

Primitivedatatypesareaspecialgroupofdatatypesthatdonotusethekeywordnewwheninitialized.Javacreatesthemasautomaticvariablesthatarenotreferenceswhichmakesthemsmallandsimpleva

[Themostcommonprimitivetypesusedinthiscourseareint(forintegers)anddouble(fordecimals).]

DataType Size Exampledata Datadescription


boolean 1bit true,false Storetrue/falseflags

Storeintegersfrom
byte 1byte(8bits) 12,128
127to128

char 2bytes 'A','5','#' StoreasingleUnicodecharacter

Storeintegersfrom
short 2bytes 6,14,2345
32768to32767
Storeintegersfrom
int 4bytes 6,14,2345
2147483648to2147483647

Storeintegersfrom
long 8bytes 34591111,2
9223372036854775808to9223372036854775807

Storeapositiveornegativedecimalnumberfrom
float 2bytes 3.124,.07242
1.4023x1045to3.4028x10+38

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 3/14
07/01/2015 Modules:PrintModule
double 4bytes .0000456,3.7 Storeapositiveornegativedecimalnumberfrom
4.9406x10324to1.7977x10308

Declaringvariablesandusingliterals

Declaringvariablesandusingliterals

Thekeywordnewisnotusedwheninitializingavariableofaprimitivetype.Instead,aliteralvalueisassignedtoeach
variableuponinitialization.Aliteralcanbeanynumber,text,orotherinformationthatrepresentsavalue.

Givenbelowareexamplesofdeclaringavariableandassigningitaliteralvalue:

booleanresult=true
charcapicalD='D'
byteb=100
shorts=10000
inti=10000
longtotal=9999999
longss_num=999_99_99
doubled1=123.4
doubled2=1.234e2
floatf1=123.4f

Somenotesontheabove:

Thevaluesofd1andd2arethesame.Theinitialisationofd2showshowscientificnotationcanbeusedtosetthevalues.

Thevaluesfortotalandss_numarethesame.Theinitialisationofss_numshowshowunderscorescanbeusedtoseparatenumbersforreadability.

Casting(convertonetypetoanother)

Casting(convertonetypetoanother)

ItispossibleinJavatoconvertonedatatypetoanother,thisiscalledcasting.
Ifyoucastonetypetoanothertype,youareexplicitlyconvertingtheitemfromit'soriginaltypetothetypethatyouspecify.

Belowisanexamplewhereavariableoftypedoubleiscasttoaninteger:

doublemyDouble=123.4
intmyInt=(int)myDouble

Later,wewilllearnwhattheconsequencesofdoingthisare.

JavaSE7Binaryliterals

JavaSE7Binaryliterals

InJavaSE7andlater,binaryliteralscanbeexpressedusingthebinarysystembyaddingtheprefixes0bor0Btothenumber.

BinaryliteralsareJavaintvalues.Javabyteandshortvaluesrequireacasttopreventaprecisionlosswarning
fromthecompiler.

BinaryLiteralsareusedforcalculations,comparisons,andlowlevelprogramming,suchaswritingdevicedrivers,lowlevelgraphics,communicationsprotocolpacketassembly,anddecoding.

Usingbinaryliteralstorepresentvaluesforcomparisonsandcalculationsissubstantiallyfasterthanusingvaluesoftheactualdatatype.Modernhighperformanceprocessorsusuallyperformcalculationsonin
whyuseliterals?

Itisstilloptimaltouseliteralsforoverallpower/performancebecausetheyuselessresources.

Intheexamplebelowthebinaryvalueiscastedandstoredasabytetype.

byteaByte=(byte)0b00100001

Ruleswhenchoosingavariablename

Rulesforvariablenames

BeforewegobacktoourAndroidapplicationandtestourcode,weneedtoknowalittlebitmoreaboutvariablenames.

Youmustfollowthefollowingruleswhenchoosingthenameforavariable:

DonotuseaJavakeywordorreservedword.

Donotuseaspaceinthevariablename.

Useacombinationoflettersandnumbers.

Youmayuseonlyacombinationoflettersoracombinationoflettersandnumbers.

Neverstartwithanumber.

Theonlysymbolsallowedaretheunderscore(_)andthedollarsign($).

Conventionsforvariablenames:

Whileconventionsarenotrules,mostJavaprogrammersfollowtheseconventions:

Neverusethe$symbolinavariablename.

Usefullwordsinsteadofcrypticabbreviations.

Donotusesinglelettervariables.Ifallofyourvariablesaresingleletters,itwillaffectthereadabilityofyourcode.

Ifyourvariablenameconsistsofoneword,spellthatwordinalllowercaseletters.

Ifyourvariablenameconsistsofmorethanoneword,usealllowercaseforthefirstword,thencapitalizethefirstletterofeachsubsequentword(thisiscalledlowerCamelCase).

Ifyourvariableisaconstant,useallcapitallettersandseparatewordswiththeunderscore.

Usenamesthatexpressthepurposeofthevariable.

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 4/14
07/01/2015 Modules:PrintModule
Forexample:intPI=3.14159
PIisagoodchoicefornamingthisnumberbecauseitallowsyoutorecallwhatthevariableis.

IncludingvariablesinAndroid

IncludingvariablesinAndroid

Eclipse2
StartEclipse

Wearenowreadytogobacktoourprogrammingenvironmentandimplementwhatwe'velearnedthusfar.

OpentheapplicationLesson1.

Opentheapplication.Thelayoutofyourapplicationshouldbevisible(activity_main.xml)

Ifnot,activateit.

TheOutlineshouldbevisible.

Activity

UpdatingthetextView1field'snametosomethingmoreappropriate

Whenwe'vecreatedthefieldsonthelayoutofourapplication,we'veacceptedthegenericnames.Nowthatweknowaboutvaraiablenames,weshouldusemoreappropriatefieldnames.Wecannowchange

AltertheId'sforbutton1andtextView1tobtnPressandtxtShow.

Whenyouarerequestedtoupdatereferences,selectYesandaccepttherestofthedefaultoptions.

Youcantickthe"Donotshowagain"forfuturereferences.

ThefieldnamesinOutlinewillnowlooksomethingsimilarto:

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 5/14
07/01/2015 Modules:PrintModule

The"type"ofwidgetisindicatednexttoeachvariable,examplebtnPressisoftypeButtonandtxtShowisoftypeTextView.

Thisisimportanttoknowwhenwestartaddressingthedifferentwidgetsinourcode

Displaysomething...

Atthisstagewearereadytodisplaysomethinginourapplication.

InLesson1,clickonsrc.Thencom.example.lesson1>doubleclickonMainActivity.java.

Thisisweretheactualcodinggoes.Seethescreendumpbelow.

Thisiswherewearegoingtoenterthecodeforourapplication.

Forthisexamplewearegoingtodeclareanumberofintanddoublevariables,dosomecalculationsanddisplaytheanswerintxtShowfield.

Intheindicatedarea,justbelowsetContentView(R.layout.activity_main)enterthefollowingcode:

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

//thisiswheremycodingwillgo
//myvariables
inttest1=20
inttest2=40
doubletest3=50.3
doubletest4=45.5
inttotal1,finalTotal
doubletotal2
total1=(test1+test2)/2//determinetheaverageoftest1andtest2
total2=(test3+test4)/2//determinetheaverageoftest3andtest4
finalTotal=total1+(int)total2
}

Wearenotyetdisplayingtheresults,butitisALWAYSagoodideatofirstcomplilethecodebeforecontinuingwithmorecode.Compileandrunitandifthereareerrors,fixit.

ErrorinJavaisindicatedwithalittleyellowbulbandaredcross,nexttothelineofcodewheretheerroris.

Somenotesonaddingcomments

Somenotesonaddingcomments

TherearemorethanonewaytoaddcommentsinourJavacode.Themostpopularwaysare:

//Mycomments.Thecompilerignoreseverythingtotheendoftheline

/*Mycomments.WhenIamaddingcommentsthat
aredisplayedovermorethanonerow.
Thecompilerignoreseverythinguntilitreaches*/

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 6/14
07/01/2015 Modules:PrintModule

/**Thisisaadocumentationcomment.
*Theauthorofthisis@PeterSeopa
*andisprocessedbyJavadoctools
*togenerateJavadocumentation
*/

SomenotesonthesyntaxofJavacode

SomenotesonthesyntaxofJavacoding

InJavaablockofcodeisplacedbetweencurlybrackets{}.

Itisalwaysagoodideatoaddsomecommentstoyourblockofcode.Thiswillhelpyou(andotherprogrammers)toreadyourcodeeasily.

EachstatementinJavaendswithasemicolon:

Displayingtheresultinatextfield

Displayingtheresultinatextfield

Whenyouaresatisfiedthattherearenoerrorsinthecode,thenproceedwiththefollowingcode.Inthiscodewearegoingtodisplaytheanswer(finalTotal)intextViewfieldtxtShow

Followthenextstepsverycarefully...(enterthecodeafteryourlastcodethatyou'veentered).

//displayfinalTotalintheapplication
//linktxtShowtoavariableshow
finalTextViewshow=(TextView)findViewById(R.id.txtShow)

NoticethatwhenyoustartwiththeR.idthatalistofvaluesaredisplayedtohelpyoutochoosefrom.SelecttxtShow.

YouwillalsonoticethatTextViewisunderlinedinredandthatJavadisplaysanerrormessagenexttoit.ThisisbecausewehavenotyetimportedtheTextViewwidgetclass.Luckyforus,Ec

Movethecursorofyourmouseto"hover"overTextView.Amenuwillappear.SelectfromthismenuImport'TextView'(android.widget).

Whatwe'vedoneistocreateanewinstanceoftheclassTextViewandwecallitshow.(Youmaynotrecognisealltheterminologyatthisstage,butyouwillaswecontinuewiththecourse.)

Theinstanceshowhasanumberofmethods(oractions)thatitcanperform.Tofindoutwhatthesemethodsare,typein:show.

Theinstancethatyou'vetypedinthedot(.)alistofmethodsappear.ScrolldownuntilyoufindsetText(Charsequencetext):v

Thefollowingwillnowappearinyourcode:show.setText(text)

Weneedtoexchangethe(text)partwithwhatwewouldliketobedisplayed.InthisinstancefinalTotal.

Unfortunatelythetypesdiffer.show.setText(text)expectsatextvalueandfinalTotalisoftypeint.

But,wecanconverttheinttoString.Wehaven'tasyetdiscussedStrings(text)inJava,butatthisstage,replacetextwiththefollowingcodethatwillconverttheintvalueto

show.setText(String.valueOf(finalTotal))

Compileyourapplication.Fixanyerrors.Runit.

Activatingthebutton

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 7/14
07/01/2015 Modules:PrintModule
Activatingthebutton

Youshouldnowbewonderingwhattodowiththeotherthreewidgets,editText1,editText2andbtnPress.

Wellletsaddsomecodingtothebutton.InthiscodingwewillthendisplaythefirstnameandsecondnamethattheuserentersinthetxtShowfieldafterthebuttonispressed.

Forthisweneedtocreateablockofcodeforthebutton.

Afteryourlastlineofcode,typeinthefollowingandresolvethewidgets,asinthepreviousinstance,byhoveringthemouseontheunderlineredline.Import'Button'(android.widget)

Buttonbut1=(Button)findViewById(R.id.btnPress)

WehavenowcreatedanewinstanceoftheclassButtonandhavecalledtheinstancebut1.

but1hasanumberofmethodsthatitcanaccessanduse.

Wearegoingtodothesameasinthepreviousinstance,butthereisatwisttothis.Followmystepsverycarefully....

Typeinbut1.setOnClickListener(l)

Changethecodewiththefollowingcode(youcancopyandpastemycodefromhere):

but1.setOnClickListener(newOnClickListener(){
publicvoidonClick(Viewv){
//Thisiswhereyourcodewillgo



}//endofonClick
})

Resolvetheunderlinedissues(View)and(OnClickListener)byhoveringthemousepointerandimportingtherelevantclasses.

Itmaybeagoodideatocopytheabovecodesomewherewhereyoucangetholdofitagain.Whenyoucreateanewbutton,thenjustreplacethenameofthebutton(inthiscasebut1

Nowaddcodingwhereitisindicated//Thisiswhereyourcodewillgo

JustaswiththefinalTotal,declarenewinstancesforeachoftheTextViews,editText1andeditText2.
Thereafter,usetheinstanceshowoftxtShowtodisplaythefirstname(editText1)andsecondname(editText2).

Notethatyoudon'tneedtoconvertanything,sincetheinputvalueswillbeintext(String)format.

//Thisiswhereyourcodewillgo

finalEditTextname1=(EditText)findViewById(R.id.editText1)
Stringn1=name1.getText().toString()//gettingtheinfofromthescreen

finalEditTextname2=(EditText)findViewById(R.id.editText2)
Stringn2=name2.getText().toString()

show.setText(n1+""+n2)


}//endofonClick

Compile,fixanyerrorsandrunyourcode.

Notice,thatasyouopentheapplication,thevalueoffinalTotalwillbedisplayed,butwhenyoupressthebutton,theinformationinthetoptwofieldswillbedisplayed.

IfyoureallystrugglethenyoucandownloadthecodefromAdditionalResources:SnippetsofCodingtheMainActivity.javafileforLesson1.

But,youMUSTtryanddothecodingyourself.ThatistheONLYwayinwhichyouwilllearn.

Podcast
Buttons_TextView_EditView
Downloadandwatchtheabovepodcastshouldyouneedmoreguidance.

Scopeofavariable

Scopeofavariable

Scopeisusedtodescribetheblockofcodewhereavariableexistsinaprogram.Itispossibleformultiple
variableswiththesamenametoexistinaJavaProgram.

Inmostcasestheinnermostvariablehasprecedence.

Avariableexistsonlyinsidethecodeblockinwhichitisdeclared.Oncethefinalbraceoftheblockisreachedthevariablegoesoutofscopeandisnolongerrecognizedasadeclaredvariable.

Thescopeisdeterminedbyabeginandanendcurlybracket.{}

TheEclipseenvironmenthelpsusinunderstandingthescopeofvariablesbetter.

GobacktoMainActivity.java.
Clickonthe(minus)nexttoeachblockofcoding,untilonlythefollowingisvisible.

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 8/14
07/01/2015 Modules:PrintModule


Clickonthe+(plus)signnexttoprotectedvoidonCreate(BundlesavedInstanceState).

Theblock(scope)ofcodethatarebetween{}arenowvisible.

Noticethatthereisaseperateblock(scope)ofcodeforButtonbut1.Alsonotethatthereisa+(plus)nexttoit.Indicatingthatthisisaseperateblockofcodeandthevariablesintheouterb
block.

Totestit....

Clickonthe+(plus)todeflatetheblockofcodeforbut1.

Anywhereinthisblock,typeinthefollowingcode:finalTotal=finalTotal*10

YouwillnoticethatfinalTotalisunderlinedinred,indicatedthatthereisasyntaxerror.ThisisbecausethevariablefinalTotalwasdeclaredintheouterblockofcode,butitisNOTvisible

Eachvariableisboundtoitsscope.

Wewilllearnlateronhowtosolvethisbydefiningclassesandprocedures/functions.

Arithmeticoperators

Arithmeticoperators

Javahasseveralarithmeticoperatorstoperformmathematicaloperations,andunaryoperatorstoperformoperationssuchasincrementinganddecrementingavaluebyone.

Belowisalistoftheseoperators

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 9/14
07/01/2015 Modules:PrintModule


Symbol Operatordescription
+ Addition
Subtraction

* Multiplication

/ Division(findsthequotient)

% Modular(findstheremainder)

++ Increment(addone)

Decrement(subtractsone)

ArithmeticOperatorsPrecedence

ArithmeticOperatorsPrecedence
Allmathexpressionsareevaluatedaccordingtothefollowingtheorderofprecedence:
Expressionsinparenthesisarehandledfirst.
Allmultiplication,division,andmodularoperationsarehandlednext,workingfromlefttoright.
Finally,alladditionandsubtractionarehandled,workingfromlefttoright.

IncrementsandDecrements

Incrementsanddecrementsarehandledfirstforpreincrementnotationandlastforpostincrementnotation.

Preincrementnotation:++x

Postincrementnotation:x++

Examples:
Preincrementnotation:
intx=3
++x//xisequalto4
z=++x//xisequalto5,THENzisequalto5

Postincrementnotation:
intx=3
x++//xisequalto4
z=x++//zisequalto4,THENxisequalto5

AssignmentOperator

Javausesthe=(equalsign)astheassignmentoperator.

Theevaluationoftheexpressionontherightisassignedtothememorylocationontheleft.

intx=4,y=5,z=10,total=12

total=x+y*z
Whenthislineofcodeisexecuted,thevaluefortotalhaschanged.

Theblueboxesshowwhatisineachmemorylocationofx,y,z,andtotal.

Nowthememorylocationtotalisassignedthevalueof4+5*10,whichis54.

Youcanthinkoftheassignmentoperatorlikeanarrowpointingtotheleft.Everythingontherightwillgointothe
memorylocationontheleft.Howwillmemorychangewhenthislineisexecuted?

x=totalx+y*(zx)

Let'scompleteitbyfillinginthevalues:

x=544+5*(104)

x=544+5*(6)//brackets(parenthesis)arecalculatedfirst

x=544+30//multiplicationiscalculatednext

x=50+30//restofcalculationishandledfromlefttoright

x=80

Truncation

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 10/14
07/01/2015 Modules:PrintModule
Truncation
Whatwillbethevalueoftotalwhenthecodebelowisexecuted?

intx=4,y=5,z=10,total=12
total=z/(4*5)

Thecorrectansweris0.Whydoesn't0.5display?


Sincetotalisaninteger,thesystemwillstoreanintegervalueastheresultofthecalculation.
Thedecimalportionoftheansweristruncatedratherthanroundedtoproducethefinalintegeranswerof0.


Truncationistheconceptofalwaysroundingthenumberdowntothenearestintegerlessthanthevalue.

Forexample,7.8wouldtruncateto7.

BeingawareoftruncationwillhelpasyoutakeaclassicmathematicalformulaandconvertittoJavacode.

Forexample,hereisaformulaforthevolumeofaconefromGeometry.


Aprogrammermightwritethefollowingtocreateaprogramtocalculatethevolume:

doubleheight=4,radius=10,volume
volume=1/3*3.14*radius*radius*height

Unfortunately,theJavaprogramwillincorrectlycalculatetheansweras0.

Workingfromlefttoright,theprogramdivides1by3.

Javaconsiders1and3tobeliteralintegersanddoesintegerdivisionwhere.33...istruncatedto0.

Howwouldyoucorrectthis?

Thereareafewwaystoforceaformulatonottruncateavalue.

1.Movethefractiontotheend.ThiswayJavawillalwaysbeusingadoubleandanintegerandwillimplicitlyconverttheanswertoadoubleandnottruncate.

doublevolume=3.14*radius*radius*height*1/3

2.Makeoneoftheliteralintegersintoaliteraldouble.ThiswayJavawillalwaysbeusingadoubleandan
integerandwillimplicitlyconverttheanswertoadoubleandnottruncate.

doublevolume=1/3.0*3.14*radius*radius*height

TheJavaAPI

TheJavaAPI
ManymathexerciseswillrequiretheuseofthemethodsintheJavaMathandStringclasses.

YoucanfindadescriptionofallJavamethodsintheonlineJavaAPI.

UnderstandinghowtonavigatethisvastlibraryofstandardmethodsandclasseswillaidyouinwritingJavaprograms andreusingmanycodeblocksthathavealreadybeencreatedbyothers.

WhyusetheAPI?
OnemajorbenefittohaveaccesstotheJavaAPIisacommonconceptforprogrammerscalledcodereuse.

Ratherthancodingexcessitems,youmayusetheAPItofindhowtoaccessexistingcodethatdoesexactlywhatyouwant.
Thiswillreducespendingtimeonreproducingalreadyexistingcodeandmakeyourprogrammingmuchmoreefficient.

Usingasearchengine,searchforkeywordsJavaAPI.

Therearemanyeditions.ReviewtheStandardEditionforJava7:
http://docs.oracle.com/javase/7/docs/api/

ExaminetheMathclassandseeifyoucanfindavalueforpiandamethodforcomputingthesquarerootofanumber.Therearealsoveryhandymethodssuchasrandom,min,max

Youdon'tneedtorememberallofthem,buttherearesomemethodsthatareusedoftenandyoushouldknowthembyheart.

Android:Volumeapp

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 11/14
07/01/2015 Modules:PrintModule

Android:Volumeapp

Activity

WearenowreadytocreateanewapplicationinAndroidwherewecantestyournewskillsandknowledge.

Wearegoingtocreateanapplicationwiththefollowingspecifications(specs):

1)Androidapplication
2)Onescreen
3)Purpose:Tocalculatethevolumeofabox
5)Layout:

Onefieldtoaskthenameoftheuser
Threeinputfieldsforheight,depth,length.(Thevaluescanbeenteredasdecimals,e.g.4.25)
Onebuttonthatwilldothecalculations
Onedisplayfield

Trytocodeitandifyougetstuckviewanexampleofthecode:MainActivity_volume.javainAdditionalResources.

ButyouMUSTtryanddoitonyourown,otherwiseyouarenevergoingtomasterit!!!

Activity

TestourknowledgeinAndroidSpinapp

Forthisexamplewearegoingtocreateanapplicationwiththefollowingspecifications(specs):

1)Androidapplication
2)Onescreen
3)Purpose:Theuserwillenteranyintegernumberandtheappwillgenerateanumberbetween0andtheusernumber.
5)Layout:
Onefieldtorequesttheuserforanumber
Onebuttonthatwillgeneratearandomnumber
Onedisplayfieldforthegeneratedrandomnumber

Trytocodeityourselfandifyougetstuckviewanexampleofthecode:MainActivity_spin.javainAdditionalResources.

ButyouMUSTtryanddoitonyourown,otherwiseyouarenevergoingtomasterit!!!

String(introduction)

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 12/14
07/01/2015 Modules:PrintModule
String(introduction)

Whilewewerecodingtheapplications,we'vecomeaccrossanumberofinstanceswherewe'veusedStrings.ThereareanumberofmanipulationsthatyoucandowithStrings.

StringisNOTaprimitivetype,butaclass.


Stringscanberepresentedwiththechartype

TheStringtypecanrepresentmultiplecharacters

Stringscanbecombinedwiththe+sign

Stringsshouldalwaysbeinitializedusing=

RefertoJavaAPIforStringmethods.

TheStringclassisimmutable,sothatonceitiscreatedaStringobjectcannotbechanged.TheStringclasshasanumberofmethods,someofwhichwillbediscussedbelow,thatappeartom

Sincestringsareimmutable,whatthesemethodsreallydoiscreateandreturnanewstringthatcontainstheresultoftheoperation.

Stringmethods

Methodsthatareusedtoobtainbutdonotchangeanyinformationaboutanobjectareknownasaccessormethods.

Belowareanumberoftheseaccessormethods.

Assumethatthefollowingisdeclared:

StringmyString="JavaProgramming"
StringthatString="isfun"

accessormethod description example
intlength() Returnsthelengthofthestring intlen=myString.length()

booleanmatches() Determineswhetherstringsmatch.Returnstrueorfalse. booleanmatch=myString.matches(thatString)

booleanisEmpty() Determineswhetherstringisempty.Returnstrueorfalse booleanisEmpty=myString.isEmpty()

myString=myString.replace('o','0')
Stringreplace(oldChar,newChar) ReturnsanewstrtingresultingfromreplacingoccurencesofoldCharwithnewChar

StringtoLowerCase() Convertsallthecharacterstolowercase myString=myString.toLowerCase()

StringtoUpperCase() Convertsallthecharacterstouppercase myString=myString.toUpperCase()

Stringconcat() Concatenates(puttogether)twoormoreStrings. myString=myString.concat("").concat(thatString)

WewillbelookingatStringsinmoredetailinalaterlesson.

Logicoperators

Logicoperators
Whenyouareworkingwithnumbers(primitivetypes)youwilloftenneedtocomparevaluesusinglogicaloperators.

Javahasthreelogicoperatorsthatcanbeusedtocombinebooleanexpressionsforcomplexexpressions.Theyare:

Logicoperator Meaning
&& AND

|| OR

! NOT

Wewillbeusingtheselogicoperatorsduringthecourse.

Reflection

Reflection

Blogger
Nowitisyourturn...

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 13/14
07/01/2015 Modules:PrintModule

Inthebloggeraddablogentry.LabelitLesson1.Inthisblog,enterashortsummaryforyourselfofeverythingthatwe'velearned.Specificallythosecomponentsthatyou'vebattledwithandhow

Remembertokeepnotesandupdatesinyourlittleblackbook.

Clickhere

https://my.unisa.ac.za/portal/tool/af26fe3b1a704e149b94f45b7f9e75d6/print_module.jsf?printModuleId=258408454 14/14

S-ar putea să vă placă și