Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: N OV. 1 5 T H INSTRUCTOR: JIAYIN WANG 1 Notice Assignment ◦ ClassExercise19isassigned ◦ Homework8isassigned ◦ BothHomework8andExercise19areduethisSunday 2 Review do/while Loop Thewhileloopisnottheonlyindefiniteloop Inawhileloopthetestexpressionisevaluatedbeforeenteringtheloop Thismeansitispossiblethattheloopcodeisneverexecuted Butsometimesweknowthatweneed... atleastonepassthroughtheloop Forsituationslikethisthedo/whileloopisabetterchoice Inado/whileloopthetestexpressionisevaluated... atthebottomoftheloop... aftertheloopcodehasbeenexecutedatleastonce 3 do/while Loop Ithasthefollowingsyntax do{ STATEMENT; ... }while(TEST_EXPRESSION); Theloopbodywillalwaysbeexecutedatleastonce Afterthat,theloopwillcontinue... aslongasthetestexpressionistrue 4 do/while Loop Let'srewritetheprogramthatrollsdice... usingado/whileloop importjava.util.*; publicclassDoWhile{ publicstaticvoidmain(String[]args){ RandomranFactory=newRandom(); intsum; do{ //rollthediceonce intdie1=ranFactory.nextInt(6)+1; intdie2=ranFactory.nextInt(6)+1; sum=die1+die2; System.out.println(die1+"+"+die2+"="+sum); }while(sum!=7); } } $javaDoWhile 5+5=10 1+1=2 1+4=5 4+5=9 4+3=7 5 The boolean Data Type Thebooleandatatypeallowsonlytwopossiblevalue • true • false Booleanexpressionsareexpressions... whosevaluecanonlybetrueorfalse trueandfalsearereservedwordsinJava Theyarebooleanliterals Youcanassignavaluetoitusingaliteral booleantest=true; Youcanassignavaluetoitusingacomplexexpression booleaneven=(number%2==0); 6 Logical Operators InJavayoucanformbooleanexpressionsusinglogicaloperators Operator Meaning Example AND (conjunction) (2 == 2) && (3 < 4) TRUE || OR (disjunction) (1 < 2) || ( 2 == 3) TRUE ! NOT (negation) ! (2 == 2) FALSE && Value TheNOToperator,!... reversesthetruthvalueofitsoperands Soiftheoperandistrue... theNOToperatormakesitfalse... andviceversa 7 Logical Operators WecanexpressthisinatruthtableforNOT,! HereisthetruthtableforAND,&& andthetruthtableforOR,|| 8 Updated Order of Precedence Nowthatwehavethreenewoperators... wehavetoseehowtheyfitintotheorderofprecedence Description Operators unary operators ! ++ -- + - multiplicative operators * / % additive operators + - relational operators < > <= >= equality operators == != logical AND && logical OR || assignment operators = += -= *= /= %= &&= ||= Dealingwithlogicaloperators, JavawillevaluateNOT,!, thenAND,&&... andfinallyOR,|| 9 Short-Circuited Evaluation JavainheritsafeatureoftheClanguagecalledshort-circuitedevaluation WheneverabooleanexpressionusetheAND,&&,orOR,||,operators... Javawillstoptheevaluatingtheexpressionifthevalueofthefirst operand... determinesthevalueoftheexpressionasawhole Forexample,ifwehavetheexpression stop<s.length()&&s.charAt(stop)!='' Thereisnoneedtoevaluatethesecondoperand s.charAt(stop)!='‘ ifweknowthefirstoperandisfalse stop<s.length() 10 Short-Circuited Evaluation sincebothoperandsmustbetruefor&&tobetrue Ifthefirstoperandisfalse... weknowthewholeexpressionisfalse... withouthavingtogofurther Similarly,ifwehavetheexpression height>5||width>5 Thereisnoneedtolookatthevalueofwidth... ifweknowheightisgreaterthan5 Anothertermforthisfeatureislazyevaluation 11 Boolean Variables and Flags Sometimes,whileprocessingdata,youwanttotakenoteofaspecial condition Whenthespecialconditionoccurs,aflagisset Thisallowstheprogrammertoseparatetheactionthatsetstheflag... fromtheresponsetothataction Flagsarebooleanvariablesthatareinitiallysettofalse Thevalueofaflagissettotrue,whensomethingspecialorunusual happens Flagsareoftenusedinloops Theyareoftenusedinwhileloopstosignalthattheworkisdoneand thattheloopshouldstop 12 Boolean Variables and Flags Thismakethiscodeslightlylonger... butisalsomakesitmorereadable... becausewecanassignanametothetestcondition Ifwewerewritingadatingprogram... wemightassignnamestocertainconditions... tomakehowwemakeourdecisionsclearer booleancute=(looks>=9); booleansmart=(IQ>125); booleanrich=(income>100000); booleangood_catch=cute&&smart&&rich; Sometimesabooleanvariable... isusedtorecordanunusualcondition Suchvariablesarecalledflags 13 Boolean Variables and Flags Flagsarebooleanvariablesthatareinitiallysettofalse Thevalueofaflagissettotruewhensomethingspecialorunusualhappens Flagsareoftenusedinloops Theyareoftenusedinwhileloopstosignalthattheworkisdoneandthatthe loopshouldstop Forexample,youasktheuserstokeepenteringapositivenumberandstop whenanegativenumberisentered. booleanisNegative=false; while(!isNegative){ System.out.print("Pleaseenterapositiveinteger:“); intnumber=console.nextInt(); if(number<0){ isNegative=true; } } 14 New Materials Outline • ScannerLookahead • DealingwithBadData • FilesandFileObjects • UsingaFileObject • ReadingaFilewithaScanner • Token-BasedProcessing 15 Scanner Lookahead AScannerobjecthas"next"methodsthatwaitforinputfromtheuser... andwhentheuserenterssomethingandhitsEnter.. readsthecharactersfromthecommandline... andturnsthemintovaluesoftherightdatatype... whicharereturnedtothecallingmethod Hereisapartiallistofthesemethods Method Description next() reads the next token and returns it as a String nextDouble() reads the next token and returns it as a double value nextInt() reads the next token and returns it as an int value nextBoolean() reads the next token and returns it as an boolean value 16 Scanner Lookahead Ifwecalloneofthesemethodsandtheuserenterssomethingthatcan't beconvertedintotherightdatatypeanexceptionisthrown Butwellwrittencodeshouldchecktheinputbeforereadingindata Tohelpyoudothis,aScannerobjecthasothermethods... whichcanlookatwhattheuserhasentered... andreturntrueifthedataentered... canbeconvertedintoaspecificdatatype Theydothiswithoutreadinginthedata 17 Scanner Lookahead Foreach"next"methodthereisacorresponding"has"method Method Description hasNext() reads the next token and returns true if it can be turned into a String value hasNextDouble() reads the next token and returns true if it can be turned into a double value hasNextInt() reads the next token and returns true if it can be turned into a int value hasNextBoolean() reads the next token and returns true if it can be turned into a boolean value Eachofthese"has"methodsreturnstrueifthevalueenteredcanbe turnedintothedatatypeneeded Thisallowsustolookatanentrywithouttryingtoconvertitintoadata type Thatmeanswecanavoidthrowinganexception 18 Scanner Lookahead Soifweareexpectinganinteger.... wecancallhasNextIntbeforecallingnextInt... andkeeppromptingforthetypeofinputweneeduntilwegetit WhenyoucallahashNextmethoditwaits.. untiltheuserhashittheenterkey Thenitlooksatthevalueentered... andreturnstrueifthevaluecanbeconvertedintothepropertype Butthevaluehasnotactuallybeenreadin 19 New Materials Outline • ScannerLookahead • DealingwithBadData • FilesandFileObjects • UsingaFileObject • ReadingaFilewithaScanner • Token-BasedProcessing 20 Dealing with Bad Data IfyouuseoneoftheScanner"has"methodsandtheuserhasentered text... whichcanbeturnedintothevalueyouwant... youcalltheappropriate"next"methodtogetthedata... andconvertitintotherightdatatype Butwhatifthedataisofthewrongtype? Youaskedforanintegerandtheusertypedin"fiftyseven”? Ifthevalueisofthewrongtype... youhavetogetridofthetexttheuserentered... inordertomakewayforanewentry 21 Dealing with Bad Data Thetexttheusertypedinisnotuseduntilyoucalloneofthe"next"methods Ifyoudon't"consume"thisinput,youwillgetaninfiniteloop Ifwerunthefollowingprogramanddon’ttypeinaninteger,wewillstuckin infiniteloop importjava.util.*; publicclassReadIntBad{ publicstaticvoidmain(String[]args){ Scannerinput=newScanner(System.in); System.out.print("Pleaseenteraninteger"); while(!input.hasNextInt()){ System.out.print("Pleaseenteraninteger"); } intnumber=input.nextInt(); System.out.println("Youentered"+number); } } $javaReadIntBad Pleaseenteraninteger: asdf Pleaseenteraninteger: Pleaseenteraninteger: Pleaseenteraninteger: Pleaseenteraninteger: … 22 Dealing with Bad Data Sincewedidnotgetridofthetextenteredbytheuser... hasNextInt()keepsreadingthesamevalueagainandagain... whichneverchanges Weneedtoreadinthevalueenteredbytheuserandthrowitaway Wedothisbycallingthenext()method next()readsintheentirelineoftextenteredbytheuser next()doesnotconvertwhattheuserentered Wecallnext()to"consume"thebadentry... tomakewayforanotherentry 23 Dealing with Bad Data Thisishowwedoit importjava.util.*; publicclassReadIntGood{ publicstaticvoidmain(String[]args){ Scannerinput=newScanner(System.in); System.out.println("Pleaseenteraninteger:"); while(!input.hasNextInt()){ $javaReadIntGood input.next();//readintheentrybutdon'tuseitPleaseenteraninteger: System.out.println("Pleaseenteraninteger:"); asdfa } Pleaseenteraninteger: intnumber=input.nextInt(); sdfgdfgh System.out.println("Youentered"+number); } Pleaseenteraninteger: } 57 Youentered57 24 New Materials Outline • ScannerLookahead • DealingwithBadData • FilesandFileObjects • UsingaFileObject • ReadingaFilewithaScanner • Token-BasedProcessing 25 Files and File Objects Oneofthemostimportantcomputerconceptsisthatofafile Afilestoredinacomputerhasanameandalocation TogetthecontentsofafileinJava,youneedtoconstructaFileobject Filef=newFile("red_sox.txt"); TheargumenttotheFileconstuctorisapathname Thepathnameuniquelyidentifiesafile Itconsistsof • Apath • Thenameofthefile Thepathisthelocationofafilespecifiedbythelistofthedirectoriesthatyoumustgo throughtogettothefile Inthiscoursewewillonlyusefilesinthecurrentdirectory Thepathnameforfilesinthecurrentdirectoryissimplythenameofthefile 26 New Materials Outline • ScannerLookahead • DealingwithBadData • FilesandFileObjects • UsingaFileObject • ReadingaFilewithaScanner • Token-BasedProcessing 27 Using a File Object OnceyouhavecreatedtheFileobject... youcancallitsmethodstogetsomeinformationaboutthefileLikethis importjava.io.*;//fortheFileclass publicclassFileInfo{ publicstaticvoidmain(String[]args){ Filef=newFile("red_sox.txt"); System.out.println("existsreturns"+f.exists()); System.out.println("canReadreturns"+f.canRead()); System.out.println("lengthreturns"+f.length()); System.out.println("getAbsolutePathreturns"+f.getAbsolutePath()); } } $javaFileInfo existsreturnstrue existsreturnstrue canReadreturnstrue lengthreturns629 getAbsolutePathreturns/Users/jiayinwang/Documents/drjava/class19/ red_sox.txtexample_code_cs114/6_chapter_examples_cs114/red_sox.txt 28 Using a File Object HerewecalledtheFileconstructorwithjustthenameofthefile Thisworksonlyifthefileisinthecurrentdirectory TheFileclassispartofthejava.iopackage,sowemusthave importjava.io.*; atthetopofanycodethatusesthisclass.”io"isshortfor"input/output" Thesyntaxofthefileconstructoris: Filef=newFile("red_sox.txt"); wearenotcreatinganewfile InsteadwearecreatinganewFileobject togetthedatainanexistingfile 29 Using a File Object HerearesomeofthemoreusefulmethodsoftheFileclass Method Description canRead() Returns true if the file exists and can be read delete() Deletes the file exists() Returns true if the file exists on the system getAbsolutePath() Returns the full path showing where this file is located getName() Returns the name of the file as a String, without any path attached isDirectory() Returns true if the "file" is a directory (folder) on the system isFile() Returns true if the file is a file (not a directory) on the system length() Returns the number of characters in this file renameTo(newName) Changes this file’s name to that of the parameter given 30 New Materials Outline • ScannerLookahead • DealingwithBadData • FilesandFileObjects • UsingaFileObject • ReadingaFilewithaScanner • Token-BasedProcessing 31 Reading a File with a Scanner object Whenweneedtogetinputfromtheuser,wecreateaScannerobject likethis Scannerconsole=newScanner(System.in); ButwecanalsouseaScannerobjecttoreadindatafromothersources AScannerobjectcanalsobeusedtoreaddatafromafile Todothis,wefirstneedtocreateaFileobjectwhichgivesusaccessto thefile OncewehavedonethiswecanthenpassthisFileobject.. totheScannerconstructor Filef=newFile("red_sox.txt"); Scannerinput=newScanner(f); 32 Reading a File with a Scanner object Afterdoingthisweneverneedfagain,sowecanshortenthecodeasfollows Scannerinput=newScanner(newFile("red_sox.txt")); Butifwetrytorunthiswegetasurprise importjava.util.*;//forScannerclass importjava.io.*;//forFileclass publicclassFileReaderBad{ publicstaticvoidmain(String[]args){ Scannerinput=newScanner(newFile("red_sox.txt")); System.out.print("JustcreatedScannerobjectforfile"); } } $javacFileReaderBad.java FileReaderBad.java:7:unreportedexceptionjava.io.FileNotFoundException;mustbecaughtortobethrown Scannerinput=newScanner(newFile("red_sox.txt")); ^ 1error 33 Reading a File with a Scanner object YouwouldthinkthataFileNotFoundExceptionwouldbesomethingyou wouldonlyseeatruntime ButaFileNotFoundExceptionisadifferentkindofexception Itisacheckedexception thatJavademandsspecialtreatmentforthem Whenyourcodecouldcreateoneoftheseexceptions... Javainsiststhatyourcodecatchthisexception... or,themethodheadermustdeclare... thatitmightthrowtheexception 34 Reading a File with a Scanner object Youdothisbyincludingathrowsclauseinthemethodheader Thiswillallowthecompiler... tocheckeverymethodthatcallsthisparticularmethod... tomakesureiteithercatchestheexception... orhasthesamethrowsclauseinit'smethodheader Athrowsclauselookslikethis publicstaticvoidmain(String[]args)throwsFileNotFoundException{ Scannerinput=newScanner(newFile("hamlet.txt")); ... } 35 Reading a File with a Scanner object Hereisanexample $catCountWords.java //Countsthenumberofwordsinafile. importjava.io.*; importjava.util.*; publicclassCountWords{ publicstaticvoidmain(String[]args)throwsFileNotFoundException{ Scannerinput=newScanner(newFile("red_sox.txt")); intcount=0; while(input.hasNext()){ Stringword=input.next(); count++; } System.out.println("Totalwords="+count); } } $javaCountWords Totalwords=181 36 New Materials Outline • ScannerLookahead • DealingwithBadData • FilesandFileObjects • UsingaFileObject • ReadingaFilewithaScanner • Token-BasedProcessing 37 Token-Based Processing Whenprogrammerstalkaboutreadinginputfromatextfile... theytalkabouttokens Atokenisastringofcharacterintheinput... setoffbyspecialcharacters Usuallytokensaresetofffromeachotherbywhitespace Thewhitespacecharactersare • Space • Tab • Newline Readingthecontentofafiletokenbytoken... iscalledtoken-basedprocessing 38 Token-Based Processing Ifwehaveafilethatcontainsthefollowing 308.214.97.4 2.8 3.94.7-15.4 2.8 Thefilecontains8tokens... eachofthetokensconsistsofdecimalnumber... sowecanusehasNextDouble()toseewhetherthereismoreinputto process... andnextDouble()toreadinthevalueofthetokenasadouble 39 Token-Based Processing //Readsaninputfileofnumbersandprintsthenumbersand //theirsum. importjava.io.*; importjava.util.*; publicclassShowSum{ publicstaticvoidmain(String[]args)throwsFileNotFoundException{ Scannerinput=newScanner(newFile("numbers.txt")); doublesum=0.0; intcount=0; while(input.hasNextDouble()){ doublenext=input.nextDouble(); count++; System.out.println("number"+count+"="+next); sum+=next; } System.out.println("Sum="+sum); } } $javaShowSum number1=308.2 number2=14.9 number3=7.4 number4=2.8 number5=3.9 number6=4.7 number7=-15.4 number8=2.8 Sum=329.29999999999995 40