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
Lab13Name:________________________Checked:______ Objectives: InthislabwewilllearnhowtoaccesstextfilesusingScannertogettheircontents.We willalsouseScannerinothernovelways,includingreadingdatadirectlyfromawebpage! Beforeyoubegin,createafolderforyourLab13files.Itisimportanttosaveallthedata andprogramfilesforthislabinthesamefolder. PartI: Preparation: Submit4files:YouVeGotMoreShoes.java,ShoeCollection.java,Shoe.java(Lab12, partB)andLab13a.java(seebelow)throughBlackboardby8:00amthemorningofLab. a.Readingvaluesfromafileandstoringtheminanarray Inpart(d)ofLab11weexploredhowtoinputvaluesfromtheuserandstoretheminan array.ReviewyourprogramLab11d.java–recallthatitusesScannertoinputinteger valuesfromtheuser.SaveacopyofthisprograminyourLab13folder,renamingitas Lab13a.java Supposeyouhavealonglistofvaluesstoredinafile,andyouwanttostoretheminan arrayof100elements.Forexample,thefile: www.csc.villanova.edu/~map/1051/s16/examples/oneHundredInts.txtYouwouldnot wanttotypethenumbersinordertoentertheminyourprograminteractively! • DownloadthisfileandsaveinyourLab13folder.OpenitinjGrasptoinspectit. • Makesurethefilewasnotcorruptedduringdownload(thishappenssometimes)–it shouldcontain100numbersandnothingelse–checkbeforeproceeding. • InJava,youcandirecttheScannertoinputfromafile,insteadoffromthekeyboard. Dothisasfollows: o IntheinstantiationoftheScannerobject,replaceSystem.inbythefilefrom whichyouare“reading”,i.e.: Scanner scan = new Scanner(new File("oneHundredInts.txt")); Importclassesfromjava.io: import java.io.*; o Add“throws IOException”totheheadingofyourmainmethod: o public static void main(String[] args) throws IOException • Sinceyouwanttoinput100numbers,youneedtoenlargethearraytohold100 integers. Troubleshooting:Remembertodouble-checkthatthefileoneHundredInts.txtissaved inthesamefolderasyourprogramandcontainsthecorrectdata(alistof100numbers). VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari PartII: b.Processingatextfile,linebyline www.csc.villanova.edu/~map/1051/s16/examples/FileInput.java //*************************************************************** // FileInput.java Author: MAP // Demonstrates the use of Scanner to read text file input. //*************************************************************** import java.util.Scanner; import java.io.*; public class FileInput { //-----------------------------------------------------------// Reads text from a file and prints it in uppercase. //-----------------------------------------------------------public static void main (String[] args) throws IOException { String line; Scanner fileScan; File myFile = new File("sample.txt"); fileScan = new Scanner (myFile); // Read and process each line of the file while (fileScan.hasNext()) { line = fileScan.nextLine(); System.out.println (line.toUpperCase()); } } } 1) Download and compile this program; create a small text file named sample.txt and save it in the same folder as the program (you can create the file directly in JGrasp – under File-> New, choose “Plain text” instead of “Java” for the file type). Run FileInput – what does it do? ____________________________________________________________________ ____________________________________________________________________ 2) Modify it to use the parameter args[0] of main() as the file name. Do this as follows: • Replace the use of File myFile = new File("sample.txt"); with File myFile = new File(args[0]); • • In jGrasp, select “Run Arguments” from the Build menu, and provide the file name as an argument (parameter) to main by typing sample.txt in the box that appears above your program. In this way, you can run your program with different files, without modifying the code. Try it with the dataset file for next project: www.csc.villanova.edu/~map/1051/s16/examples/titanic.txt VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari c.ScanningfromaString JustaswecanuseaScannertoinputfromafileorfromSystem.in,wecanalsousea Scannerto“input”fromaString! 1)Trythiscode:Lab13c.java //******************************************************************** // Lab13c.java MA Papalaskari // Simple example: scanning from a String //******************************************************************** import java.util.Scanner; public class Lab13c { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Please type 3 words: String line = scan.nextLine(); "); Scanner scanLine = new Scanner(line); String word1 = scanLine.next(); String word2 = scanLine.next(); String word3 = scanLine.next(); System.out.println("Word 1: " + word1); System.out.println("Word 2: " + word2); System.out.println("Word 3: " + word3); scanningfrom aString } } Run :Lab13c.java– what does it do? ____________________________________________________________________ ____________________________________________________________________ d.ScanningfromaStringanddoingsomethinguseful Next,wewillcreateLab13d.javabymodifyingLab13c.javasothatitdoessomething moreinterestingwiththeinput.Ournewprogramwilltreattheinputasacommandfor asimplenumericcomputation. Forexample,theinputmightbe: 55 * 83 Wewanttheprogramtocomputeandprinttheproduct4565.First,runLab13c.java withthisinputandobservehowitpicksoutthe“55”,“*”,“83”asword1,word2,and word3,respectively.NotethatthecodeusesscanLine.next()whichproducesString tokensandthatwasfinebecauseword1,word2,andword3areStrings.Butnowyouwant tousethevalues55and83asnumbers,sothevariableshavetobeoftypedouble(we VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari coulduseint,butdoublewillallowyoutohandleawiderrangeofvalues),andyou needtoobtaintheirvaluesusingscanLine.nextDouble()insteadofscanLine.next(). Canyouusetheseideastocreateasimplecalculator?Changethepromptfrom“Please enter3words”to“Calculate:” Notethatyoucantestthevalueofword2.charAt(0)toseeifitisequalto‘+’,‘*’,etc,and, accordingly,computetheresult.(Ifyouwanttobeabletohandlemorethan2operators, itisbesttouseaswitchstatement.) Sampleruns: ----jGRASP exec: java Lab13d Calculate: 9.3 + 44.7 = 54.0 ----jGRASP exec: java Lab13d Calculate: 55 * 83 = 4565.0 e.Inputdataintoanarray ThetechniquedescribedinPartsCisalsousefulforprocessingdataorganizedin columnsandinputtingthatintoanarray.GobacktothecodeforPartC(NOTPartD)and modifythecodesothatitinputs8wordsintoanarrayof8Strings.(Besuretoreplace thevariablesword1,word2etcbyanarrayword[0],word[1],etc.anduseafor-loopto gettheinput.Thewordsshouldthenbeprintedbackwards. Tabdelimiteddata: Sometimestheinputtokenscancontainspaces.Forexample,the“words”couldbe countrynames: India United States France China Germany Greece South Korea Brazil Thesearestilljust8countries!Insuchsituations,atabcanbeusedasadelimiter,sothe Stringwouldbestoredas: "India\tUnited States\tFrance\tChina\tGermany\tGreece\tSouth Korea\tBrazil" InorderforyourScannertouseadelimiterotherthanwhitespace,youneedtospecify thisbeforedoinganyinput: scanLine.useDelimiter("\t"); Samplerun: ----jGRASP exec: java Lab13d Enter 8 country names, all in one line, separated by tabs: India France Japan India Greece United States South Korea Mali South Korea United States Greece India Note:thesearetabcharacters Japan France India Mali VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari f.Processingdatafromtextfiles,organizedincolumns(CombinePartsb&e) The technique described in (e) is useful for processing text files containing data organizedincolumns.Wenowmodify FileInput.java from(b),above,sothatafterit inputseachline,itusesthetechniqueof Lab13e.java,above(i.e.,asecondScanner)to “scan”8wordsfromeachlineinthefileandstorethesewordsinanarray,thenprintthe contentsofthearraybackwards.Trythiswiththefollowingfile: http://www.csc.villanova.edu/~map/1051/s16/examples/eightwords.txt Sampleoutput: Line: India France Mali South Korea United States Greece United Arab Emirates Japan France India Line: apple orange pineapple raspbery grape persimmon fig asian pear orange apple Line: black green blue red dark gray light gray gray white black Japan asian pear white gray United Arab Emirates fig Greece persimmon light gray United States grape dark gray raspbery red blue South Korea Mali pineapple green g.(Optional)Inputdirectlyfromawebsite Wouldyoulikeyourprogramtoaccessawebsitedirectly?Hereishow.Youneedto 1)Addanotherimportdirectiveatthebeginningoryourprogram: import java.net.URL; 2)SetupyourScannertoreadfromtheurlinsteadofafile.Hereisanexample: String myurl = "http://www.csc.villanova.edu/~map/1051/s16/examples/oneHundredInts.txt"; InputStream inStream = new URL(myurl).openStream(); Scanner webScan = new Scanner (inStream); 3)Nowyoucanuse webScan asanyotherScanner object,toinputfromawebpage asifitwereanyothertextfile.Tryitwithyourprogramlab13a.java. Thistechniquewillworkwithmostwebpages,aslongastheycanbereadastext (includinghtmlfiles). VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari Lab13Comments Name:________________________ Commentsonthislab,please: Whatwasthemostvaluablethingyoulearnedinthislab? Whatdidyoulikebestaboutthislab? Wasthereanyparticularproblem? Doyouhaveanysuggestionsforimprovingthislabasaneffectivelearningexperience? VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari