Download Content - University of Stirling

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
CSCU9T4(ManagingInforma3on):
StringsandFilesinJava
CarronShankland
Content
• 
• 
• 
• 
Stringmanipula3oninJava
TheuseoffilesinJava
Theuseofthecommandlinearguments
References:
–  JavaForEveryone,2ndEdi3on(2013),byCay
Horstmann
•  Chapter02:sec3on2.3and2.5(strings)
•  Chapter07:sec3ons7.1,7.2,7.3(files)
–  Thelecturematerialcomesfromthisbook
–  M.T.GoodrichandR.Tamassia,DataStructuresand
AlgorithmsinJava,5thedi3on
•  Characterstrings(suchasthosedisplayedintheboard)are
importantdatatypesinanyJavaprogram.Wewilllearnhowto
workwithtext,andhowtoperformusefultaskswiththem.
•  Wewillalsolearnhowtowriteprogramsthatmanipulatetextfiles,
averyusefulskillforprocessingrealworlddata.
2
StringProcessingfacili3esinJava
• 
• 
• 
• 
AcommonmethodtomanipulatestringsinJavaistousethetheStringclass(youcanalso
useStringBuffer)
TheStringclassprovidesalotofusefulmethods,includingthosefor
–  crea3ngandmanipula3ngstrings
–  inspec3ngthecharactersinastring
–  spliXngupastringintotokens
Wewilltakeaquicktourofsomeofthemostusefulofthese(aZeraquickrecapofthe
featuresyouknowalready)
–  substring, trim, split
–  toUpperCase, toLowerCase
–  equals, endsWith, startsWith
–  charAt, indexOf,lastindexOf
WewillalsolookattheStringTokenizer class
TIP:RefertoJavadocs!h\p://www.cs.s3r.ac.uk/doc/java/jdk1.6/
©UniversityofS3rling
Strings
•  Manyprogramsprocesstext,notnumbers
•  Textconsistsofcharacters:le\ers,numbers,
punctua3ons,spaces,etc.
•  Whatisastring?
–  Anorderedcollec3onofcharactersofarbitrary
length
–  ConsiderS3rling,Yourock!,“67.435”,3.8x104,or
5.2e6?
–  Inour‘world’stringsdelineatedbyquota3ons:““
©UniversityofS3rling
4
•  Input
Commonusesofstrings
–  fromauser,orfroma(data)file
–  theprogrammustunderstandwhatthestringrepresents
–  makingsenseofastring(determiningitssyntax)iscalled
parsinge.g.aUrl
•  Output
–  maybeonthescreen,ortoafile
•  StringsareoZenconvertedto/fromotherformats,e.g.
–  string/numberconversionsareverycommon,including
integers,floa3ngpointnumbers
–  canalsohavegeneralstring/objectconversions
•  Asprogrammers,weneedtobeabletoprocessstrings
©UniversityofS3rling
Examplesofstringprocessing
•  Acompilertakesthetextofaprogramasinput,
anditsfirsttaskistoparsetheinput
•  Awordprocessorlookstoseewhicharethe
individualwordsofalineoftextsothatitcan
spellcheckthem.
•  AbrowsermustparseaURLintopieces:
–  whichprotocoltouse
–  whichwebservertocontact
–  whichfiletoaskforfromthatwebserver
©UniversityofS3rling
2.5 Strings
q 
The String Type:
§  Type Variable Literal
§  Stringname= Harry q 
Once you have a String variable, you can use
methods such as:
intn=name.length();//nwillbeassigned5
q 
A String s length is the number of characters
inside:
§  An empty String (length 0) is shown as §  The maximum length is quite large (an int)
Copyright © 2013 by John Wiley & Sons.
Page 7
Stringconcatena3on
•  Java:+operatorisusedtoconcatenatestrings.Putthemtogetherto
producealongerstring.Example:
–  String fName = “Harry”, String lName = “Morgan”
–  String name = fName + lName
–  Resultsinthestring:“HarryNorman”
•  Ifyou’dlikethefirstandlastnameseparatedbyaspace:
–  String name = fName + “ “ + lName
–  Resultsinthestring:“Harry Norman”
•  WhentheexpressiontotheleZorrightofa‘+’operatorisastring,
theotheroneisautoma3callyforcedtobeastring,andbothstrings
areconcatenated.Example:
–  String jobTitle = “Agent”, int empID = 7
–  String bond = jobTitle + empID
–  Resultsinthestring:“Agent7”
©UniversityofS3rling
8
2.3InputandOutput
ReadingInput
• Youmightneedtoaskforinput(akapromptforinput)
andthensavewhatwasentered.
–  Wewillbereadinginputfromthekeyboard
–  Fornow,don tworryaboutthedetails
• ThisisathreestepprocessinJava
1) ImporttheScannerclassfromits package java.util
importjava.util.Scanner;
2) SetupanobjectoftheScannerclass
Scannerin=newScanner(System.in);
3) UsemethodsofthenewScannerobjecttogetinput
intbottles=in.nextInt();
doubleprice=in.nextDouble();
Page 9
Syntax2.3:InputStatement
•  TheScannerclassallowsyoutoreadkeyboardinputfromtheuser
–  ItispartoftheJavaAPIutilpackage
Java classes are grouped into packages.
Use the import statement to use
classes from packages.
Page 10
String Input
q 
You can read a String from the console with:
System.out.print("Pleaseenteryourname:");
Stringname=in.next();
§  The next method reads one word at a time
§  It looks for white space delimiters
q 
You can read an entire line from the console with:
System.out.print("Pleaseenteryouraddress:");
Stringaddress=in.nextLine();
§  The nextLine method reads until the user hits Enter
q 
Converting a String variable to a number
System.out.print("Pleaseenteryourage:");
Stringinput=in.nextLine();
intage=Integer.parseInt(input);//onlydigits!
Page 11
Copyright © 2013 by John Wiley & Sons.
String Escape Sequences
q 
How would you print a double quote?
§  Preface the " with a \inside the double quoted String
System.out.print("Hesaid\"Hello\"");
q 
OK, then how do you print a backslash?
§  Preface the \ with another \!
System.out.print(" C:\\Temp\\Secret.txt );
q 
Special characters inside Strings
§  Output a newline with a \n System.out.print("*\n**\n***\n");
Copyright © 2013 by John Wiley & Sons.
*
**
***
Page 12
Strings and Characters
q 
Strings are sequences of characters
§  Unicode characters to be exact
§  Characters have their own type: char
§  Characters have numeric values
•  See the ASCII code chart in Appendix B
•  For example, the letter H has a value of 72 if it were a
number
q 
Use single quotes around a char
charinitial= B ;
q 
Use double quotes around a String
Stringinitials= BRL ;
Page 13
Copyright © 2013 by John Wiley & Sons.
Copying a char from a String
q 
q 
q 
Each char inside a String has an index number:
0
1
2
3
4
c
h
a
r
s
5
6
7
8
9
h
e
r
e
The first char is index zero (0)
The charAt method returns a char at a given
0
1
2
3
index inside a String:
Stringgreeting="Harry";
charstart=greeting.charAt(0);
charlast=greeting.charAt(4);
Copyright © 2013 by John Wiley & Sons.
H
a
r
r
4
y
Page 14
Copying portion of a String
q 
q 
A substring is a portion of a String
The substring method returns a portion of a
String at a given index for a number of chars,
starting at an index:
0
1
2
3
4
5
H
e
l
0
1
H
e
Stringgreeting="Hello!";
Stringsub=greeting.substring(0,2);
Stringsub2=greeting.substring(3,5);
l
o
!
Page 15
Example: initials.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.Scanner;
/**
This program prints a pair of initials.
*/
public class Initials
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// Get the names of the couple
System.out.print("Enter your first name: ");
String first = in.next();
System.out.print("Enter your significant other's first name: ");
String second = in.next();
// Compute and display the inscription
String initials = first.substring(0, 1)
+ "&" + second.substring(0, 1);
System.out.println(initials);
}
}
Copyright © 2013 by John Wiley & Sons.
Page 16
TheStringTokenizerClass
•  TheStringTokenizerclassallowsastringtobesplitintopiecesknowas
‘tokens’
•  Adelimitercharacterisspecified,andthisisusedtobreakdownthe
originalstringintotokens.Westartanewtokenevery3meadelimiter
characterisdetected.
•  Forexample,withthestring
"http://www.cs.stir.ac.uk/courses/CSC9V4/"
•  andthedelimiter'/',theindividualtokensinthatstringwouldbe
"http:","www.cs.stir.ac.uk","courses",and"CSC9V4".
•  Moreusually,withthedefaultspacecharacter delimiter,alineoftext
canbebrokenupintoindividualwords.Thisishowawordprocessor
worksoutwherewordsbeginandend.
©UniversityofS3rling
StringTokenizerExample1
StringTokenizer st;
// Declare a reference
st = new StringTokenizer("this is a test");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
Theaboveprogramproduces:
this
is
a
test
©UniversityofS3rling
StringTokenizerExample2
String input="http://www.cs.stir.ac.uk/index.htm";!
String delims= "/";!
!
StringTokenizer st; !// Declare a reference!
st = new StringTokenizer(input,delims); !
!
while (st.hasMoreTokens()) !
System.out.println(st.nextToken());
Theaboveprogramproduces:
http:
www.cs.stir.ac.uk
index.htm
©UniversityofS3rling
TheString.splitmethod
• 
• 
InJava1.5,anewmethodoftokenizingstringswasintroduced.Anaddi3onal
methodcalledsplitwasaddedtotheStringclass.
TheAPIguideforsplitis:
public String[] split(String regex)
whereregexisa‘regularexpression’orpa\ernusedtodeterminehowtobreak
uptheString.
• 
Forexamplewecouldjustusetheforwardslashdelimiterasbefore“/”,
alterna3velywecanuse“\\s+”whichmeansoneormorewhitespaces,or“two\\s
+”whichlooksfortheword‘two’followedbyoneormorewhitespaces.(What
are\\d,\\D,\\w,\\W?)
• 
• 
Regularexpressionsareverypowerfulselectors
splitreturnsanarrayoftokens;eachtokenisjustaString
h\p://ocpsoZ.org/opensource/guide-to-regular-expressions-in-java-part-1/
©UniversityofS3rling
Example:String.split
String input="http://www.cs.stir.ac.uk/index.htm";!
String delims="/";!
!
String [] tokens = input.split(delims);!
!
for (int t=0; t<tokens.length; t++)!
Theabovecodeproduces:
System.out.println(tokens[t]);
2.5
Strings
63
http: 12
// Get the names of the couple
13
www.cs.stir.ac.uk
14
System.out.print("Enter your first name: ");
15
String first = in.next();
index.htm
16
System.out.print("Enter your significant other's first name: ");
17
String second = in.next();
18
19
// Compute and display the inscription
20
©UniversityofS3rling
21
String initials = first.substring(0, 1)
22
+ "&" + second.substring(0, 1);
23
System.out.println(initials);
24
}
25 }
Program Run
Enter your first name: Rodolfo
Enter your significant other's first name: Sally
R&S
Table 9: String Operations (1)
Table 9 String Operations
Statement
Result
Comment
string str = "Ja";
str = str + "va";
str is set to "Java"
When applied to strings,
+ denotes concatenation.
System.out.println("Please"
+ " enter your name: ");
Prints
Use concatenation to break up strings
that don’t fit into one line.
team = 49 + "ers"
team is set to "49ers"
Because "ers" is a string, 49 is converted
to a string.
String first = in.next();
String last = in.next();
(User input: Harry Morgan)
first contains "Harry"
last contains "Morgan"
The next method places the next word
into the string variable.
String greeting = "H & S";
int n = greeting.length();
n is set to 5
Each space counts as one character.
String str = "Sally";
char ch = str.charAt(1);
ch is set to 'a'
This is a char value, not a String. Note
that the initial position is 0.
String str = "Sally";
String str2 = str.substring(1, 4);
str2 is set to "all"
Extracts the substring starting at
position 1 and ending before position 4.
String str = "Sally";
String str2 = str.substring(1);
str2 is set to "ally"
If you omit the end position, all
characters from the position until the
end of the string are included.
String str = "Sally";
str2 is set to "a"
Extracts a String of length
Copyright © 2013 by John Wiley & Sons.
Please enter your name:
Page 22
Table 9: String Operations (2)
Page 23
Copyright © 2013 by John Wiley & Sons.
Formatted Output
q 
Outputting floating point values can look strange:
q 
Price per liter:
1.21997
To control the output appearance of numeric
variables, use formatted output tools such as:
System.out.printf( %.2f ,price);
Price per liter: 1.22
System.out.printf( %10.2f ,price);
Price per liter:
1.22
10 spaces
2 spaces
§  The %10.2fis called a format specifier
Page 24
Format Types
q 
Formatting is handy to align columns of output
q 
You can also include text inside the quotes:
System.out.printf( Priceperliter:%10.2f ,price);
Page 25
Summary: Strings
q 
q 
q 
q 
q 
q 
q 
q 
Strings are sequences of characters.
The length method yields the number of characters in a
String.
Use the + operator to concatenate Strings; that is, to put
them together to yield a longer String.
Use the next (one word) or nextLine (entire line)
methods of the Scanner class to read a String.
Whenever one of the arguments of the + operator is a
String, the other argument is converted to a String.
If a String contains the digits of a number, you use the
Integer.parseIntor Double.parseDouble method to
obtain the number value.
String index numbers are counted starting with 0.
Use the substring method to extract a part of a String
Copyright © 2013 by John Wiley & Sons.
Page 26
Files
7.1 Reading and Writing Text Files
q 
Text Files are very commonly used to store
information
§  Both numbers and words can be stored as text
§  They are the most portable types of data files
q 
The Scanner class can be used to read text files
§  We have used it to read from the keyboard
§  Reading from a file requires using the File class
q 
The PrintWriter class will be used to write text
files
§  Using familiar print, println and printf tools
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 28
Text File Input
q 
Create an object of the File class
§  Pass it the name of the file to read in quotes
FileinputFile=newFile("input.txt");
q 
Then create an object of the Scanner class
§  Pass the constructor the new File object
Scannerin=newScanner(inputFile);
q 
Then use Scanner methods such as:
§ 
§ 
§ 
§ 
§ 
§ 
next()
nextLine()
hasNextLine()
hasNext()
nextDouble()
nextInt()...
while(in.hasNextLine())
{
Stringline=in.nextLine();
//Processline;
}
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 29
Text File Output
q 
Create an object of the PrintWriter class
§  Pass it the name of the file to write in quotes
PrintWriterout=newPrintWriter("output.txt");
•  If output.txt exists, it will be emptied
•  If output.txt does not exist, it will create an empty file
PrintWriter is an enhanced version of PrintStream
• System.outis a PrintStream object!
System.out.println( HelloWorld! );
q 
Then use PrintWriter methods such as:
§  print()
out.println("Hello,World!");
§  println() out.printf("Total:%8.2f\n",totalPrice);
§  printf()
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 30
Closing Files
q 
You must use the close method before file
reading and writing is complete
q 
Closing a Scanner
while(in.hasNextLine())
{
Stringline=in.nextLine();
//Processline;
}
in.close();
q 
Your text may not be saved
to the file until you use the
close method!
Closing a PrintWriter
out.println("Hello,World!");
out.printf("Total:%8.2f\n",totalPrice);
out.close();
Page 31
Copyright © 2013 by John Wiley & Sons.
All rights reserved.
Exceptions Preview
q 
One additional issue that we need to tackle:
§  If the input file for a Scanner doesn’t exist, a
FileNotFoundException occurs when the
Scanner object is constructed.
§  The PrintWriter constructor can generate this
exception if it cannot open the file for writing.
•  If the name is illegal or the user does not have the
authority to create a file in the given location
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 32
Exceptions Preview
§  Add two words to any method that uses File I/O
publicstaticvoidmain(String[]args)throws
FileNotFoundException
•  Until you learn how to handle exceptions yourself
Copyright © 2011 by John Wiley & Sons. All rights reserved.
Page 33
And an important import or two..
q 
Exception classes are part of the java.io package
§  Place the import directives at the beginning of the source
file that will be using File I/O and exceptions
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.PrintWriter;
importjava.util.Scanner;
publicclassLineNumberer
{
publicvoidopenFile()throwsFileNotFoundException
{
...
}
}
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 34
Example: Total.java (1)
More import statements
required! Some examples may
use importjava.io.*;
Note the throws clause
Page 35
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Example: Total.java (2)
Don’t forget to close the files
before your program ends.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 36
Common Error 7.1
q 
Backslashes in File Names
§  When using a String literal for a file name with path
information, you need to supply each backslash twice:
FileinputFile=newFile("c:\\homework\\input.dat");
§  A single backslash inside a quoted string is the escape
character, which means the next character is interpreted
differently (for example, \n for a newline character)
§  When a user supplies a filename into a program, the
user should not type the backslash twice
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 37
Common Error 7.2
q 
Constructing a Scanner with a String
§  When you construct a PrintWriter with a String, it writes
to a file:
PrintWriterout=newPrintWriter("output.txt");
§  This does not work for a Scanner object
Scannerin=newScanner("input.txt");//Error?
§  It does not open a file. Instead, it simply reads through
the String that you passed ( input.txt )
§  To read from a file, pass Scanner a File object:
Scannerin=newScanner(newFile ( input.txt ) );
§  or
FilemyFile=newFile("input.txt");
Scannerin=newScanner(myFile);
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 38
7.2 Text Input and Output
q 
q 
In the following sections, you will learn how to
process text with complex contents, and you will
learn how to cope with challenges that often occur
with real data.
Reading Words Example:
Mary had a little lamb
input
while(in.hasNext())
{
Stringinput=in.next();
System.out.println(input); output
}
Mary
had
a
little
lamb
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 39
Processing Text Input
q 
There are times when you want to read input by:
§ 
§ 
§ 
§ 
q 
Each Word
Each Line
One Number
One Character
Processing input is required for
almost all types of programs that
interact with the user.
Java provides methods of the Scanner and
String classes to handle each situation
§  It does take some practice to mix them though!
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 40
Reading Words
q 
q 
In the examples so far, we have read text one line at a time
To read each word one at a time in a loop, use:
§  The Scanner object s hasNext()method to test if there
is another word
§  The Scanner object s next() method to read one word
while(in.hasNext())
{
Stringinput=in.next();
System.out.println(input);
}
§  Input:
Mary had a little lamb
Mary
Output: had
a
little
lamb
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 41
White Space
q 
q 
The Scanner’s next() method has to decide
where a word starts and ends.
It uses simple rules:
§  It consumes all white space before the first character
§  It then reads characters until the first white space
character is found or the end of the input is reached
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 42
White Space
q 
What is whitespace?
§  Characters used to separate:
•  Words
•  Lines
Common White Space
Space
\n
NewLine
\r
Carriage Return
\t
Tab
\f
Form Feed
Mary had a little lamb,\n
her fleece was white as\tsnow
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 43
The useDelimiter Method
q 
The Scanner class has a method to change the
default set of delimiters used to separate words.
§  The useDelimitermethod takes a String that lists all
of the characters you want to use as delimiters:
Scannerin=newScanner(...);
in.useDelimiter("[^A-Za-z]+");
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 44
The useDelimiter Method
Scannerin=newScanner(...);
in.useDelimiter("[^A-Za-z]+");
§  You can also pass a String in regular expression format
inside the String parameter as in the example above.
§  [^A-Za-z]+says that all characters that ^not either AZuppercase letters A through Z or a-zlowercase a
through z are delimiters.
§  Search the Internet to learn more about regular
expressions.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 45
Summary: Input/Output
q 
q 
q 
Use the Scanner class for reading text files.
When writing text files, use the PrintWriter class
and the print/println/printf methods.
Close all files when you are done processing them.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 46
Summary: Processing Text Files
q 
q 
The next method reads a string that is delimited
by white space.
nextDouble (and nextInt…) read double,
Integer, respectively.
§  Should be used with hasNextDouble and hasNextInt
respectively to avoid exceptions
§  They do not consume white space following a number
q 
Next lecture
§  How to read complete lines with mixed input (data record)
§  How to read one character at a time
§  Command line arguments
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 47
Reading Characters
q 
There are no hasNextChar() or nextChar()
methods of the Scanner class
§  Instead, you can set the Scanner to use an empty
delimiter ("")
Scannerin=newScanner(...);
in.useDelimiter("");
while(in.hasNext())
{
charch=in.next().charAt(0);
//Processeachcharacter
}
§  next returns a one character String
§  Use charAt(0) to extract the character from the String
at index 0 to a char variable
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 48
Classifying Characters
q 
The Character class provides several useful
methods to classify a character:
§  Pass them a char and they return a boolean
if(Character.isDigit(ch))…
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 49
Reading Lines
q 
Some text files are used as simple databases
§  Each line has a set of related pieces of information
§  This example is complicated by:
China 1330044605
•  Some countries use two words India 1147995898
United States 303824646
–  United States
§  It would be better to read the entire line and process it
using powerful String class methods
while(in.hasNextLine())
{
Stringline=in.nextLine();
//Processeachline
}
q 
nextLine()reads one line and consumes the ending \n
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 50
Breaking Up Each Line
q 
Now we need to break up the line into two parts
§  Everything before the first digit is part of the country
§  Get the index of the first digit with Character.isdigit
inti=0;
while(!Character.isDigit(line.charAt(i))){i++;}
Page 51
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Breaking Up Each Line
§  Use String methods to extract the two parts
United States
StringcountryName=line.substring(0,i);
Stringpopulation=line.substring(i);
//removethetrailingspaceincountryName
countryName=countryName.trim();
303824646
trim removes white space at
the beginning and the end.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 52
Or Use Scanner Methods
q 
Instead of String methods, you can sometimes use
Scanner methods to do the same tasks
§  Read the line into a String variable United States 303824646
•  Pass the String variable to a new Scanner object
§  Use ScannerhasNextInt to find the numbers
•  If not numbers, use next and concatenate words
ScannerlineScanner=newScanner(line); Remember the
next method
StringcountryName=lineScanner.next(); consumes white
while(!lineScanner.hasNextInt())
space.
{
countryName=countryName+""+lineScanner.next();
}
Page 53
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Converting Strings to Numbers
q 
Strings can contain digits, not numbers
§  They must be converted to numeric types
§  Wrapper classes provide a parseInt method
3
0
3
8
2
4
6
4
6
Stringpop= 303824646 ;
intpopulationValue=Integer.parseInt(pop);
3
.
9
5
StringpriceString= 3.95 ;
intprice=Double.parseInt(priceString);
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 54
Converting Strings to Numbers
q 
Caution:
§  The argument must be a string containing only digits
without any additional characters. Not even spaces are
allowed! So… Use the trim method before parsing!
intpopulationValue=Integer.parseInt(pop.trim());
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 55
Safely Reading Numbers
q 
Scanner nextInt and nextDouble can get
confused
§  If the number is not properly formatted, an Input
Mismatch Exception occurs
§  Use the hasNextInt and hasNextDouble methods to test
your input first
if(in.hasNextInt())
{
intvalue=in.nextInt();//safe
}
q 
They will return true if digits are present
§  If true, nextInt and nextDouble will return a value
§  If not true, they would throw an input mismatch exception
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 56
Reading Other Number Types
q 
q 
The Scanner class has methods to test and read
almost all of the primitive types
Data Type
Test Method
Read Method
byte
hasNextByte
nextByte
short
hasNextShort
nextShort
int
hasNextInt
nextInt
long
hasNextLong
nextLong
float
hasNextFloat
nextFloat
double
hasNextDouble
nextDouble
boolean
hasNextBoolean
nextBoolean
What is missing?
§  Right, no char methods!
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 57
Mixing Number, Word and Line Input
q 
nextDouble (and nextInt…) do not consume
white space following a number
§  This can be an issue when calling nextLine after
reading a number
China
§  There is a newline at the end of each line 1330044605
India
§  After reading 1330044605 with nextInt
• nextLine will read until the \n (an empty String)
while(in.hasNextInt())
{
StringcountryName=in.nextLine();
intpopulation=in.nextInt();
in.nextLine();//Consumethenewline
}
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 58
Formatting Output
q 
Advanced System.out.printf
§  Can align strings and numbers
§  Can set the field width for each
§  Can left align (default is right)
q 
Two format specifiers example:
System.out.printf("%-10s%10.2f",items[i]+":",prices[i]);
§  %-10s : Left justified String, width 10
§  %10.2f: Right justified, 2 decimal places, width 10
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 59
printf Format Specifier
q 
A format specifier has the following structure:
§  The first character is a %
§  Next, there are optional flags that modify the format,
such as - to indicate left alignment. See Table 2 for the
most common format flags
§  Next is the field width, the total number of characters in
the field (including the spaces used for padding),
followed by an optional precision for floating-point
numbers
q 
The format specifier ends with the format type,
such as f for floating-point values or s for strings.
See Table 3 for the most important formats
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 60
printf Format Flags
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 61
printf Format Types
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 62
7.3 Command Line Arguments
q 
Text based programs can be parameterized by
using command line arguments
§  Filename and options are often typed after the program
name at a command prompt:
>javaProgramClass-vinput.dat
publicstaticvoidmain(String[]args)
§  Java provides access to them as an array of Strings
parameter to the main method named args
args[0]:"-v"
args[1]:"input.dat"
§  The args.length variable holds the number of args
§  Options (switches) traditionally begin with a dash Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 63
Caesar Cipher Example
q 
q 
q 
Write a program that encrypts a file – scrambles it
so it is unreadable except to those who know the
encryption method
Use a method familiar to the emperor Julius
Caesar (ignoring 2,000 years of progress in
encryption)
Replacing A → D, B → E, C → F … (shift of a fixed
length)
Copyright © 2014 University of Stirling
arguments:
• An optional -d flag to indicate decryption instead of
encryption
• The input file name
• The output file name
Caesar Cipher Example
q 
Write a command line program that uses
character
The emperor
Julius Caesar
used a simple scheme to
replacement (Caesar cipher) to:
For example,
java CaesarCipher input.txt encrypt.txt
encrypt messages.
1)  Encrypt a file provided input and output file names
encrypts the file input.txt and places the result into
>javaCaesarCipherinput.txtencrypt.txt
encrypt.txt.
2)  Decrypt
a file as anoutput.txt
option
java CaesarCipher
-d encrypt.txt
decrypts the file>javaCaesarCipher–dencrypt.txtoutput.txt
encrypt.txt and places the result into output.txt.
Plain text
M
e
e
t
m
e
a
t
t
h
e
Encrypted text
P
h
h
w
p
h
d
w
w
k
h
Figure 1
Caesar Cipher
Copyright © 2013 by John Wiley & Sons. All rights reserved.
section_3/CaesarCipher.java
1
2
3
4
import
import
import
import
Page 65
java.io.File;
java.io.FileNotFoundException;
java.io.PrintWriter;
java.util.Scanner;
CaesarCipher.java (1)
This method uses file I/O and
can throw this exception.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 66
CaesarCipher.java (2)
If the switch is present, it is the
first argument
Call the usage method to
print helpful instructions
Page 67
Copyright © 2013 by John Wiley & Sons. All rights reserved.
CaesarCipher.java (3)
Process the input file one
character at a time
Don’t forget the close the files!
Example of a usage method
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 68
Steps to Processing Text Files
1) Understand the Processing Task
-- Process on the go or store data and then process?
2) Determine input and output files
3) Choose how you will get file names
4) Choose line, word or character based input processing
-- If all data is on one line, normally use line input
5) With line-oriented input, extract required data
-- Examine the line and plan for whitespace, delimiters…
6) Use methods to factor out common tasks
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 69
Summary: Input/Output
q 
q 
q 
q 
Use the Scanner class for reading text files.
When writing text files, use the PrintWriter class
and the print/println/printf methods.
Close all files when you are done processing them.
Programs that start from the command line receive
command line arguments in the main method.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 70
Summary: Processing Text Files
q 
q 
q 
q 
q 
The next method reads a string that is delimited
by white space.
The Character class has methods for classifying
characters.
The nextLine method reads an entire line.
If a string contains the digits of a number, you use
the Integer.parseInt or Double.parseDouble
method to obtain the number value.
Programs that start from the command line
receive the command line arguments in the main
method.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 71