Download File Input using Scanner – Warm-up Exercise

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
FileInputusingScanner–Warm-upExercise
Objectives:
LearnhowtoinputdatafromtextfilesusingScanner.
Wewillbemodifyingthecodeofpart(d)inLab10togetinputfromafile.
Inthatprogramweexploredhowtoinputvaluesfromtheuserandtostorethemin
anarray.
1.ReviewyourprogramLab10d.java–recallthatitusesScannertoinputinteger
valuesfromtheuserandtostorethesevaluesinanarray.Makesureitstillworks.
RenameitasLab10file.javabeforeyoumakeanychanges.
2.DownloadthefileoneHundredInts.txt,beingcarefultosaveitinthesamefolder
andtousethesamename(oneHundredInts.txt).
NOTE:OpenoneHundredInts.txtinjGrasptoinspectit.Verifythatthefilewasnotcorrupted
duringdownload(thishappenssometimes).Itshouldcontain100numbersandnothing
else–checkcarefullyanddeleteanythingextraneousbeforeproceeding.
3.Ourgoalistoinputthevaluesfromthisfileandtostoretheminanarrayof100
elements(insteadofhavingtotypethemininteractively).Followthesestepsto
directtheScannertoinputfromthefile(insteadofinputtingfromthekeyboard,as
itiscurrentlyimplemented):
o IntheinstantiationoftheScannerobject,replaceSystem.inbythefile
fromwhichyouare“scanning”,i.e.:
Scanner scan = new Scanner(new File("oneHundredInts.txt"));
o
Importclassesfromjava.io:
import java.io.*;
o
Add“throws IOException”totheheadingofyourmainmethod:
public static void main(String[] args) throws IOException
4.Sinceyouwanttoinput100numbers,youneedtoenlargethearraytohold100
integers.
Troubleshooting:Remembertodouble-checkthatthefileoneHundredInts.txtissavedinthe
samefolderasyourprogram,containsthecorrectdata(alistof100numbers),andthatyou
spelleditsnamecorrectlyinyourprogram.
VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari
PartA: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 to test it (best to use a
plain text editor or use jGrasp: FileàNewà Otherà Plain text). Type a few lines of text
into your file and save as sample.txt in the same folder. 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/f16/examples/titanic.txt 3.Modifywhatgetsprintedintheinnerloop(marked//****inthecodeabove)and
tryagain.Forexample,youmighttry:
System.out.println (line + "****" + line);
•
VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari
PartB.ScanningfromaString
JustaswecanuseaScannertoinputfromafileorfromSystem.in,wecanalsousea
Scannerto“input”fromaString!
1)Trythiscode:ScanFromString.java
//********************************************************************
// ScanFromString.java
MA Papalaskari
// Simple example: scanning from a String
//********************************************************************
import java.util.Scanner;
public class ScanFromString
{
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 :ScanFromString.java– what does it do?
____________________________________________________________________
____________________________________________________________________
PartC.ASimpleCalculator
Next,wewillcreateCalculator.javabymodifyingScanFromString.javasothatit
doessomethingmoreinterestingwiththeinput.Ournewprogramwilltreatthe
inputasacommandforasimplenumericcomputation.
Forexample,theinputmightbe:
55 * 83
Wewanttheprogramtocomputeandprinttheproduct4565.First,run
ScanFromString.javawiththisinputandobservehowitpicksoutthe“55”,“*”,“83”
asword1,word2,andword3,respectively.NotethatthecodeusesscanLine.next()
whichproducesStringtokensandthatwasfinebecauseword1,word2,andword3
areStrings.Butnowyouwanttousethevalues55and83asnumbers,sothe
variableshavetobeoftypedouble(wecoulduseint,butdoublewillallowyouto
handleawiderrangeofvalues),andyouneedtoobtaintheirvaluesusing
scanLine.nextDouble()insteadofscanLine.next().
VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari
Canyouusetheseideastocreateasimplecalculator?Changethepromptfrom
“Pleaseenter3words”to“Calculate:”
Notethatyoucantestthevalueofword2.charAt(0)toseeifitisequalto‘+’,‘*’,etc,
and,accordingly,computetheresult.(Ifyouwanttobeabletohandlemorethan2
operators,itisbesttouseaswitchstatement.)
Sampleruns:
----jGRASP exec: java Lab13d
Calculate:
9.3 + 44.7
= 54.0
----jGRASP exec: java Lab13d
Calculate:
55 * 83
= 4565.0
PartD.Inputdataintoanarray
ThetechniquedescribedinPartsCisalsousefulforprocessingdataorganizedin
columnsandinputtingthatintoanarray.GobacktothecodeforPartB(NOTPart
C)andmodifythecodesothatitinputs8wordsintoanarrayof8Strings.(Besure
toreplacethevariablesword1,word2etcbyanarrayword[0],word[1],etc.anduse
afor-looptogettheinput.Thewordsshouldthenbeprintedbackwards.
Tabdelimiteddata:
Sometimestheinputtokenscancontainspaces.Forexample,the“words”couldbe
countrynames:
India United States France China Germany Greece South Korea Brazil
Thesearestilljust8countries!Insuchsituations,atabcanbeusedasadelimiter,so
theStringwouldbestoredas:
"India\tUnited States\tFrance\tChina\tGermany\tGreece\tSouth Korea\tBrazil"
InorderforyourScannertouseadelimiterotherthanwhitespace,youneedto
specifythisbeforedoinganyinput:
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
Note:thesearetabcharacters
India
Japan
France
India
Mali
f.Processingdatafromtextfiles,organizedincolumns(CombinePartsb&e)
The technique described in (e) is useful for processing text files containing data
organized in columns. We now modify FileInput.java from (b) , above, so that
afteritinputseachline,itusesthetechniqueof Lab13e.java,above(i.e.,asecond
Scanner) to “scan” 8 words from each line in the file and store these words in an
array, then print the contents of the array backwards. Try this with the following
file:
http://www.csc.villanova.edu/~map/1051/s16/examples/eightwords.txt
VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari
Sampleoutput:
Line: India
France
Mali
Mali
South Korea
United States
Greece
United Arab Emirates
Japan
France
India
Line:
apple
orange
pineapple
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
South Korea
raspbery
red
blue
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,toinputfroma
webpageasifitwereanyothertextfile.Tryitwithyourprogramlab13a.java.
Thistechniquewillworkwithmostwebpages,aslongastheycanbereadastext
(includinghtmlfiles).
VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari
Lab13CommentsName:________________________
Commentsonthislab,please:
Whatwasthemostvaluablethingyoulearnedinthislab?
Whatdidyoulikebestaboutthislab?
Wasthereanyparticularproblem?
Do you have any suggestions for improving this lab as an effective learning
experience?
VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari