Download Class 20

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CS/IT 114
Introduction to Java, Part 1
FALL 2016
CLASS 20: N OV. 1 7 T H
INSTRUCTOR: JIAYIN WANG
1
Notice
Assignment
◦ ClassExercise20isassigned
◦ BothHomework8andExercise19,20areduethisSunday
2
Review
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
3
Scanner Lookahead
Ifwecalloneofthesemethodsandtheuserenterssomethingthatcan't
beconvertedintotherightdatatypeanexceptionisthrown
Butwellwrittencodeshouldchecktheinputbeforereadingindata
Tohelpyoudothis,aScannerobjecthasothermethods...
whichcanlookatwhattheuserhasentered...
andreturntrueifthedataentered...
canbeconvertedintoaspecificdatatype
Theydothiswithoutreadinginthedata
4
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
5
Scanner Lookahead
Soifweareexpectinganinteger....
wecancallhasNextIntbeforecallingnextInt...
andkeeppromptingforthetypeofinputweneeduntilwegetit
WhenyoucallahashNextmethoditwaits..
untiltheuserhashittheenterkey
Thenitlooksatthevalueentered...
andreturnstrueifthevaluecanbeconvertedintothepropertype
Butthevaluehasnotactuallybeenreadin
6
Dealing with Bad Data
IfyouuseoneoftheScanner"has"methodsandtheuserhasentered
text...
whichcanbeturnedintothevalueyouwant...
youcalltheappropriate"next"methodtogetthedata...
andconvertitintotherightdatatype
Butwhatifthedataisofthewrongtype?
Youaskedforanintegerandtheusertypedin"fiftyseven”?
Ifthevalueisofthewrongtype...
youhavetogetridofthetexttheuserentered...
inordertomakewayforanewentry
7
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:
…
8
Dealing with Bad Data
Sincewedidnotgetridofthetextenteredbytheuser...
hasNextInt()keepsreadingthesamevalueagainandagain...
whichneverchanges
Weneedtoreadinthevalueenteredbytheuserandthrowitaway
Wedothisbycallingthenext()method
next()readsintheentirelineoftextenteredbytheuser
next()doesnotconvertwhattheuserentered
Wecallnext()to"consume"thebadentry...
tomakewayforanotherentry
9
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
10
Files and File Objects
Afileisalineararrangementofdatainacomputerhasanameandalocation
TogetthecontentsofafileinJava,youneedtoconstructaFileobject
Filef=newFile("red_sox.txt");
TheargumenttotheFileconstuctorisapathname
Thepathnameuniquelyidentifiesafile
Itconsistsof
• Apath
• Thenameofthefile
Thepathisthelocationofafilespecifiedbythelistofthedirectoriesthatyou
mustgothroughtogettothefile
Inthiscoursewewillonlyusefilesinthecurrentdirectory
Thepathnameforfilesinthecurrentdirectoryissimplythenameofthefile
11
Using a File Object
OnceyouhavecreatedtheFileobject…
youcancallitsmethodstogetsomeinformationaboutthefile
TheFileclassispartofthejava.iopackage,sowemusthave
importjava.io.*;
atthetopofanycodethatusesthisclass.”io"isshortfor"input/output"
Thesyntaxofthefileconstructoris:
Filef=newFile("red_sox.txt");
wearenotcreatinganewfile
InsteadwearecreatinganewFileobject
togetthedatainanexistingfile
12
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
13
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);
14
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
15
Reading a File with a Scanner object
YouwouldthinkthataFileNotFoundExceptionwouldbesomethingyou
wouldonlyseeatruntime
ButaFileNotFoundExceptionisadifferentkindofexception
Itisacheckedexception
thatJavademandsspecialtreatmentforthem
Whenyourcodecouldcreateoneoftheseexceptions...
Javainsiststhatyourcodecatchthisexception...
or,themethodheadermustdeclare...
thatitmightthrowtheexception
16
Reading a File with a Scanner object
Youdothisbyincludingathrowsclauseinthemethodheader
Thiswillallowthecompiler...
tocheckeverymethodthatcallsthisparticularmethod...
tomakesureiteithercatchestheexception...
orhasthesamethrowsclauseinit'smethodheader
Athrowsclauselookslikethis
publicstaticvoidmain(String[]args)throwsFileNotFoundException{
Scannerinput=newScanner(newFile("hamlet.txt"));
...
}
17
Token-Based Processing
Whenprogrammerstalkaboutreadinginputfromatextfile...
theytalkabouttokens
Atokenisastringofcharacterintheinput...
setoffbyspecialcharacters
Usuallytokensaresetofffromeachotherbywhitespace
Thewhitespacecharactersare
• Space
• Tab
• Newline
Readingthecontentofafiletokenbytoken...
iscalledtoken-basedprocessing
18
Token-Based Processing
Ifwehaveafilethatcontainsthefollowing
308.214.97.4
2.8
3.94.7-15.4
2.8
Thefilecontains8tokens...
eachofthetokensconsistsofdecimalnumber...
sowecanusehasNextDouble()toseewhetherthereismoreinputto
process...
andnextDouble()toreadinthevalueofthetokenasadouble
19
New Materials
Outline
• try/catchStatement
• StructureofFilesandConsumingInput
• KeepingTrackofPositionWhenReadingaFile
• ScannersasArguments
• UsingMoreThanOneScanner
20
try/catch Statement
Wehavediscussedquiteabitaboutexceptions…
thatanyexceptioncanbecaughtinsideyourJavacode
Youdothiswithatry/catchstatement
Ithasthefollowingformat
try{
STATEMENT;
...
}catch(EXCEPTION_TYPEEXCEPTION_VARIABLE){
STATEMENT;
...
}
21
try/catch Statement
Atry/catchstatementhastwocodeblocks...
Thefirstblockisthetryblock
Thisblockcontainsmethodsthatmightthrowanexception...
andallthecodethatdependsonthosemethods
AstheJavainterpretermarchesthroughthecode...
whenitisforcedtothrowanexceptionsinsidethetryblock...
itstopsexecutingthecodeinsidethisblock
Insteaditlooksforacatchblock...
thatcatchestheparticularkindofexception...
thatwasthrown
22
try/catch Statement
Eachcatchblockcatchesaparticularkindofexception
Ifthereisnocatchblockforthespecificexception...
theinterpreterwilllookforacatchblock...
insidethemethodthatcalledthemethodwheretheexceptionoccurred
Ifnocatchblockisfound,youwillgetaruntimeerror
Youmustdeclarethespecifictypeofexception...
thataparticularcatchblockwillcatch...
insideparenthesesfollowingthekeywordcatch
}catch(FileNotFoundExceptione){
23
try/catch Statement
Whatyouareactuallydoinginsidetheparentheses...
isdeclaringavariablethatwillholdtheexception...
thatwascaught
Thisvariableobjectcanbeusedinsidethecatchblock...
becauseexceptionobjectshavemethods
Wewillnotbeusingthesemethodsinthiscourse...
butyoumustdeclaretheexceptionobject...
evenifyoudon'tuseit
24
try/catch Statement
Let'slookatanexample
importjava.io.*;
importjava.util.*;
publicclassTryCatch{
publicstaticvoidmain(String[]args){
Stringfilename="foo.txt";
try{
Scannerinput=newScanner(newFile(filename));
System.out.println("CreatedScannerobjecton"+filename);
}catch(FileNotFoundExceptione){
System.out.println("Couldnotfind"+filename);
}
}
}
$javaTryCatch
Couldnotfindfoo.txt
25
New Materials
Outline
• try/catchStatement
• StructureofFilesandConsumingInput
• KeepingTrackofPositionWhenReadingaFile
• ScannersasArguments
• UsingMoreThanOneScanner
26
Structure of Files and
Consuming Input
Javathinksofthefileaasonedimensionallistofcharacters
Wetendtothinkofalineoftextasaunit...
buttoJava,alineisjustaseriesofcharacters...
followedbythenewlinecharacter
YoucanaskJavatoreadalineoftext...
butthatisnotwhatwearedoing…
whenweusenextDouble()
27
Structure of Files and
Consuming Input
Thismethodjustreadsthenexttokenandturnsitintoadoubleifitcan
AsfarasnextDouble()isconcerned...
thenewlineisjustanotherwhitespacecharacter
Thecharacterliteral'\n'representsthenewlinecharacter
Whereweseethefileas
308.214.97.4
2.8
3.94.7-15.4
2.8
Javaseesthefileas
308.214.97.4\n2.8\n\n3.94.7-15.4\n2.8
28
New Materials
Outline
• try/catchStatement
• StructureofFilesandConsumingInput
• KeepingTrackofPositionWhenReadingaFile
• ScannersasArguments
• UsingMoreThanOneScanner
29
Keeping Track of Position
When Reading a File
Whenreadingthroughafile,theFileobjectkeepstrackofthecurrent
position
Itdoesthisbykeepingapointer...
tothecurrentpositioninthefile
Thispointeriscalledaninputcursor
Asyoureadtextfromthefile...
theinputcursoradvances
WhenyoufirstcreateaFileobject...
it'sinputcursorpointstothebeginningofthefile
30
Keeping Track of Position
When Reading a File
SowhenwecreatedaScannerobject...
usingaFileobjectconnectedtonumbers.txt…
theinputcursorlookslikethis
308.214.97.4\n2.8\n\n3.94.7-15.4\n2.8
↑
AfterthefirstcalltonextDouble()..
thecursorwillpointtothespaceafterthefirstnumber
308.214.97.4\n2.8\n\n3.94.7-15.4\n2.8
↑
31
Keeping Track of Position
When Reading a File
Wecallthisprocessconsuminginput
Consuminginputdoesnotchangethefile
Itmerelychangesthevalueoftheinputcursor
intheFileobject...
usedbytheScannerobject
AftertheScannerreads2.8...
theinputcursorpointstoanewlinecharacter
308.214.97.4\n2.8\n\n3.94.7-15.4\n2.8
↑
32
Keeping Track of Position
When Reading a File
WhathappensthenexttimenextDouble()iscalled?
Thescannersimplyskipsoverthetwonewlinecharacters...
andreads3.9...
becausethenewlinecharacterhasnospecialmeaning...
totheScannerobject
It'ssimplyawhitespacecharacter...
thathastobeskippedtogettothenexttoken
Whenthelasttokenhasbeenconsumed...
theinputcursorisattheatendofthefile
308.214.97.4\n2.8\n\n3.94.7-15.4\n2.8
↑
33
Keeping Track of Position
When Reading a File
IfthecodecalledtheScannerobjectforanothervalueatthispoint...
theinterpreterwouldthrowaNoSuchElementException
The"has"methodswillallreturnfalse...
whentheygettotheendofthefile
Thatiswhyyoushouldalwayscalla"has"method...
beforecallinga"next"method...
whenreadingafile
Scannerobjectsaredesignedtoprocessafile...
bymovingforwardonly
Theyprovidenomethodsformovingbackwardsinafile
Ifyouneedtoreadsomethingfromapreviouspointinthefile...
youhavetocreateanewScannerobject
34
New Materials
Outline
• try/catchStatement
• StructureofFilesandConsumingInput
• KeepingTrackofPositionWhenReadingaFile
• ScannersasArguments
• UsingMoreThanOneScanner
35
Scanners as Arguments
IfyoupassaScannerobjecttoamethodasaparameter...
theScannerdoesnotresettothebeginningofthefile...
justbecauseitissenttoamethod
TheFileobjectinsidetheScannerobject...
keepstrackofthecurrentpositioninthefile
EvenifyouhandthesameScannerobject...
toseveraldifferentmethods...
theFileobjectalwaysknowsthecurrentpositioninthefile
InthecodebelowwecreateasingleScannerobject...
andpassitasaparametertoamethod...
inthreeseparatemethodcalls
36
Scanners as Arguments
//DemonstratesaScannerasaparametertoamethodthat
//canconsumeanarbitrarynumberoftokens.
importjava.io.*;
importjava.util.*;
publicclassShowThreeSums{
publicstaticvoidmain(String[]args)throwsFileNotFoundException{
Scannerinput=newScanner(newFile("numbers.txt"));
processTokens(input,2);
processTokens(input,3);
processTokens(input,2);
}
publicstaticvoidprocessTokens(Scannerinput,intn){
doublesum=0.0;
for(inti=1;i<=n;i++){
doublenext=input.nextDouble();
System.out.println("number"+i+"="+next);
sum+=next;
}
System.out.println("Sum="+sum);
System.out.println();
}
}
37
Scanners as Arguments
Whenwerunthiscodeonnumbers.txt...
whichcontains
308.214.97.4
2.8
3.94.7-15.4
2.8
weget
$javaShowThreeSums
number1=308.2
number2=14.9
Sum=323.09999999999997
number1=7.4
number2=2.8
number3=3.9
Sum=14.1
number1=4.7
number2=-15.4
Sum=-10.7
Heretheinputfromthefileisshowninred
NoticethattheinputcursoroftheScannerobject...
neverresetstothebeginningofthefile
Thismayseemsurprising...
butitmakestheScannerobjectsimpler...
andinengineering,simplerisalmostalwaysbetter
38
New Materials
Outline
• try/catchStatement
• StructureofFilesandConsumingInput
• KeepingTrackofPositionWhenReadingaFile
• ScannersasArguments
• UsingMoreThanOneScanner
39
Using More Than One Scanner
Ifyouwanttoreadindatafromafile...
butyoualsowanttoprompttheuserforthefilename
youneedtwodifferentScannerobjects
SoyourcodewillhavetwoScannerobjects
Onetoreadthenameofthefilefromtheuser
Theothertoreadthefileitself
YouneedanewScannerobject...
foreachnewsourceofinput
HereisavariantoftheShowSumclass
thatpromptstheuserforthenameofthefile
40
Using More Than One Scanner
//VariationofShowSumthatpromptsforafilename.
importjava.io.*;
importjava.util.*;
publicclassShowSumPromptForFile{
publicstaticvoidmain(String[]args)throwsFileNotFoundException{
System.out.println("Willaddaseriesofnumbersfromafile.");
System.out.println();
Scannerconsole=newScanner(System.in);
System.out.print("Whatisthefilename?");
Stringname=console.nextLine();
Scannerinput=newScanner(newFile(name));
System.out.println();
$javaShowSumPromptForFile
Willaddaseriesofnumbersfromafile.
Whatisthefilename?numbers.txt
doublesum=0.0;
intcount=0;
number1=308.2
while(input.hasNextDouble()){
number2=14.9
doublenext=input.nextDouble();
number3=7.4
count++;
number4=2.8
System.out.println("number"+count+"="+next);
number5=3.9
sum+=next;
number6=3.9
}
number7=-15.4
System.out.println("Sum="+sum);
number8=2.8
}
Sum=329.29999999999995
}
41
Class Quiz 20
1.Whatisatoken?
astringofcharactersseparatedfromotherstringsbywhitespace
2.Whatarethethreewhitespacecharacters?
space,tab,andnewline
3.WhenyouhavecreatedaScannerobjecttoreadafilethathasmanylines,will
youhavetodosomethingspecialwhenyoucometotheendofthefirstline?
no.the"next"methodswillignoreanewlinecharacter
4.WhatwillhappenifyoucallnextInt()andthenexttokencannotbeturnedinto
aninteger?
anexceptionwillbethrown
5.WhatdoestheFileobjectusetokeeptrackofitspositioninafile?
aninputcursor
42
Class Quiz 20
6.Wheredoesthethingmentionedabovepointtobeforeithasconsumed
anyinputinafile?
justbeforethefirstcharacterinthefile
7.CanaScannergobothforwardsandbackwardsinafile?
no,itcanonlygoforward
8.Ifyouwantedtoasktheuserforthenameofafileandthenwantedto
readinputfromthatfile,howmanyScannerobjectswouldyouneedto
create?
two.onetogetthenameofthefilefromtheuser
andtheothertoreadthefile
9.Whatarethetwopartsofapathname?
thepathandthefilename
43