Upload
stella-dotson
View
36
Download
0
Embed Size (px)
DESCRIPTION
Chapter 6 Using Classes: Dates and I/O Streams. Date, DateFormat, GregorianCalendar Classes Reading from Keyboard with Input Stream Using Streams to Read and Write Text Files Database Management Systems. Classes: Uses in Java. Package related group of methods - PowerPoint PPT Presentation
Citation preview
Programming and Problem SolvingWith Java
Copyright 1999, James M. Slack
Chapter 6Using Classes: Dates and I/O StreamsDate, DateFormat, GregorianCalendar ClassesReading from Keyboard with Input StreamUsing Streams to Read and Write Text FilesDatabase Management Systems
Programming and Problem Solving With Java 2
Classes: Uses in JavaPackage related group of methods
Example: Math classUse methods with name of the class
int x = Math.abs(y);
Make a new data typeExample: Turtle classMake an object of the class
Turtle myTurtle = new Turtle();
Use methods with objectsmyTurtle.move(100);
Programming and Problem Solving With Java 3
Classes: Why Use?Make Java extensible
Can add new features to the languageCan build on existing features, or
start from scratchExample: String class
String not primitive in JavaWorks almost like a primitive type
Many standard classesDates User Interface ExceptionsFiles Networking DatabasesApplets Data storage ElectronicThreads Random numbers commerce
Programming and Problem Solving With Java 4
Classes: Why Use?Classes form basis of program developmentGiven problem, Java programmer should
Look for classes appropriate to the problem domain If there are no existing classes
•Extend existing classes, or•Write new classes from scratch
Classes are essence of object-oriented programming
Programming and Problem Solving With Java 5
Date Classes: DateThree of Java's many Date
classesDateDateFormatGregorianCalendar
The Date classDate object represents a particular point in timeTo create an object of the class
Date aDate = new Date();
Date constructor initializes with today's date and time
new operatormakes object
Constructor
Programming and Problem Solving With Java 6
Date Classes: DateFormatDisplay Date object
Date aDate = new Date();System.out.println(aDate);
Mon Apr 20 16:49:32 CST 1998
DateFormat: format Date object for displayDateFormat is abstract: can't create objects with newTo create a DateFormat object
DateFormat aDateFormatter = DateFormat.getDateInstance();
Use format() method to format a Date objectDate aDate = new Date();DateFormat aDateFormatter = DateFormat.getDateInstance();String aString = aDateFormatter.format(aDate);
20-Apr-1998
Programming and Problem Solving With Java 7
Date Classes: DateFormatFour date formats
Specify format in DateFormat.getDateInstance()Date aDate = new Date();DateFormat aDateFormatter = DateFormat.getDateInstance(DateFormat.FULL);String aString = aDateFormatter.format(aDate);
Monday, April 20, 1998
Can specify locale in DateFormat.getDateInstance()DateFormat aDateFormatter = DateFormat.getDateInstance(Locale.FRANCE);
Format Example
DateFormat.SHORT 4/20/98
DateFormat.MEDIUM 20-Apr-98
DateFormat.LONG April 20, 1998
DateFormat.FULL Monday, April 20, 1998
Programming and Problem Solving With Java 8
Date Classes: GregorianCalendarUse GregorianCalendar object to set day
// Example of GregorianCalendar class. This program initializes a// GregorianCalendar object to October 15, 1999, converts the object// to a Date object, then displays the result with DateFormat.
import java.util.GregorianCalendar;import java.util.Calendar;import java.text.DateFormat;import java.util.Date;
class SetDate{ public static void main(String[] args) { // Make a DateFormat object that formats in FULL style DateFormat aDateFormatter = DateFormat.getDateInstance(DateFormat.FULL);
// Initialize aGregCal to October 15, 1999 GregorianCalendar aGregCal = new GregorianCalendar(1999, Calendar.OCTOBER, 15);
// Convert aGregCal to aDate object Date aDate = aGregCal.getTime();
// Display the date with the formatter System.out.println(aDateFormatter.format(aDate)); }}
Programming and Problem Solving With Java 9
Date Classes: Discarding ObjectsCreate new GregorianCalendar object, assign to
variableGregorianCalendar someDate = new GregorianCalendar(1999, Calendar.MAY, 12);
Create another object, assign to same variablesomeDate = new GregorianCalendar(1998, Calendar.APRIL, 20);
Garbage collection: Clean up discarded objects
May 12, 1999
someDate
April 20, 1998
May 12, 1999
someDate
This object is nolonger in use
Programming and Problem Solving With Java 10
Input StreamsStream is flow of data
Reader at one endWriter at the other end
Stream generalizes input & outputKeyboard electronics different from disk Input stream makes keyboard look like a disk
ReaderWriter Stream
Programming and Problem Solving With Java 11
Input Streams: Keyboard ClassHave been using Keyboard class for reading
int num = Keyboard.readInt("Enter number: ");
What's the Keyboardclass hiding?
The System..instream!
Programming and Problem Solving With Java 12
Input Streams: System.inSystem.in: the standard input stream
By default, reads characters from the keyboard
Can use System.in many waysDirectly (low-level access)Through layers of abstraction (high-level access)
Program System.in
Programming and Problem Solving With Java 13
Input Streams: Read CharactersCan read characters from System.in with read()
// Reads a single character from the keyboard and displays itclass DemonstrateRead{ public static void main(String[] args) throws java.io.IOException { char character;
// Prompt for a character and read it System.out.print("Enter a character: "); System.out.flush(); character = (char) System.in.read(); // Display the character typed System.out.println(); System.out.println("You typed " + character); }}
System.in
'f'
InputStream.read()
'f','i','r','s','t','\n','1','2','3','\n','4','2',' ','5','8','\n', ...
Programming and Problem Solving With Java 14
Input Streams: Read CharactersSystem.in.read() returns an integer
Usually cast to charchar character = (char) System.in.read();
System.in.read returns -1 if EOF detectedEOF = end of file (no more characters in stream)
Signaling EOF at keyboardControl-Z (Windows), Control-D (Unix)
Example: Read all characters in stream until EOFint intChar = System.in.read();while (intChar != -1){ // Convert to character char character = (char) intChar; System.out.println("Next character is " + character);
// Get next one intChar = System.in.read();}
Programming and Problem Solving With Java 15
Input Streams: Read CharactersExample: Count digits, letters, other characters
Part 1: Setup
// Reads text from the keyboard and displays the// number of digits, upper case letters, lower case letters, // and other characters that the user typed.
class CountCharacters{ public static void main(String[] args) throws java.io.IOException { int nextValue, numUpperCase = 0, numLowerCase = 0, numDigits = 0, numOther = 0; char nextChar;
// Display instructions System.out.println("Enter some text, terminate with EOF");
Programming and Problem Solving With Java 16
Input Streams: Read CharactersPart 2: Read and count
// Read from the input stream, count characters until no more // characters in the input stream nextValue = System.in.read(); while (nextValue != -1) { nextChar = (char) nextValue; if (Character.isDigit(nextChar)) { numDigits++; } else if (Character.isUpperCase(nextChar)) { numUpperCase++; } else if (Character.isLowerCase(nextChar)) { numLowerCase++; } else { numOther++; } nextValue = System.in.read(); }
Programming and Problem Solving With Java 17
Input Streams: Read CharactersPart 3: Display results
// Display results System.out.println(); System.out.println(); System.out.println("Number of digits: " + numDigits); System.out.println("Number of upper case letters: " + numUpperCase); System.out.println("Number of lower case letters: " + numLowerCase); System.out.println("Number of other characters: " + numOther); }}
Programming and Problem Solving With Java 18
Input Streams: Read StringsNo String-reading methods in System.inTo read strings from keyboard
First wrap System.in inside InputStreamReader objectInputStreamReader anInputStreamReader = new InputStreamReader(System.in);
InputStreamReader.read()
an InputStreamReader object
InputStream.read()
'f','i','r','s','t','1','2','3','\n','4','2',' ','5','8','\n', ...
System.in stream
'f'
Programming and Problem Solving With Java 19
Input Streams: Read StringsNext, wrap InputStreamReader object in BufferedReader object
InputStreamReader anInputStreamReader = new InputStreamReader(System.in);BufferedReader inStream = new BufferedReader(anInputStreamReader);
InputStreamReader.read()
an InputStreamReader object
InputStream.read()
'f','i','r','s','t','\n','1','2','3','\n','4','2',' ','5','8','\n', ...
System.in stream
"first"
BufferedReader.readLine()
a BufferedReader object
Programming and Problem Solving With Java 20
Input Streams: Read StringsCan combine these two statements
BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
InputStreamReader & BufferedReader in java.io.*Must import java.io.*;
Skeleton for readingimport java.io.*;
class ClassName{ public static void main(String[] args) throws java.io.IOException { // Create a buffered input stream and attach it to standard // input BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); ... }}
Programming and Problem Solving With Java 21
Input Streams: Read StringsMethods in BufferedReader
read(): Use same as System.in.read() readLine(): Returns complete line typed by user
Example: Read user's name// Reads a user's first name, middle initial,// and last name. Demonstrates use of InputStreamReader, // BufferedReader and the readLine() method.
import java.io.*;
class ReadInputAsString{ public static void main(String[] args) throws java.io.IOException { String firstName, lastName; char middleInitial; // Create an input stream and attach it to the standard // input stream BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
Programming and Problem Solving With Java 22
Input Streams: Read StringsExample: continued
// Read a line from the user as a String System.out.print("Enter your first name: "); System.out.flush(); firstName = inStream.readLine(); // Read a character from the user System.out.print("Enter your middle initial and last name: "); System.out.flush(); middleInitial = (char) inStream.read();
// Read a line from the user as a String lastName = inStream.readLine();
// Display the strings System.out.println(); System.out.println("Your name is " + firstName + " " + middleInitial + ". " + lastName); }} Enter your first name: Linda
Enter your middle initial and last name: EJones
Your name is Linda E. Jones
Programming and Problem Solving With Java 23
Input Streams: Read NumbersTo read a number from
keyboard (int, double, ...) Define a NumberFormat
object Define BufferedReader
object Use BufferedReader object
to Read response as a string Use NumberFormat object
to parse string into Number object
Convert Number object to primitive type
InputStreamReader.read()
an InputStreamReader object
InputStream.read()
'1','2','3','\n','4','2',' ','5','8','\n', ...
System.in stream
"123"
BufferedReader.readLine()
a BufferedReader object
NumberFormatter.parse()
Number(123)
Number.intValue()
123
Programming and Problem Solving With Java 24
Input Streams: Read NumbersCode to read a number from keyboard (int, double, ...)
Define a NumberFormat objectNumberFormat aNumberFormatter = NumberFormat.getInstance();
Define BufferedReader object BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
Read response as a stringSystem.out.print("Enter an integer: ");System.out.flush();String response = inStream.readLine();
Use NumberFormat object to parse string into Numberobject
Number aNumberObject = aNumberFormatter.parse(response);
Convert Number object to primitive typeint intNumber = aNumberObject.intValue();
Programming and Problem Solving With Java 25
Input Streams: Read NumbersCan combine reading, parsing, conversion steps
import java.io.*;import java.text.NumberFormat;
class ReadAnInt2{ public static void main(String[] args) throws java.io.IOException, java.text.ParseException { // Create an input stream and attach it to the standard // input stream BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
// Create a number formatter object NumberFormat aNumberFormatter = NumberFormat.getInstance();
// Prompt for input System.out.print("Enter an integer: "); System.out.flush();
// Read the response from the user, convert to Number, // then convert to int int intNumber = aNumberFormatter.parse(inStream.readLine()).intValue();
// Display the value System.out.println("You typed " + intNumber); }}
NoteParseException!
Programming and Problem Solving With Java 26
Input Streams: Multiple ValuesTo read several
values on one lineUse
StringTokenizer object
Breaks onestring into parts
Must still convertnumbers (ifnecessary)
"42","58"
StringTokenizer()
StringTokenizer.nextToken()
a StringTokenizer object
InputStreamReader.read()
an InputStreamReader object
InputStream.read()
'4','2',' ','5','8','\n', ...
System.in stream
"42 58"
BufferedReader.readLine()
a BufferedReader object
Programming and Problem Solving With Java 27
Input Streams: Multiple ValuesHow to use StringTokenizer
Get string to break apart somehow Initialize object with string to break apart
StringTokenizer tokenizer = new StringTokenizer("42 58");
Use nextToken() method to get partsString token;token = tokenizer.nextToken();System.out.println(token); // Displays 42token = tokenizer.nextToken();System.out.println(token); // Displays 58
Can use hasMoreTokens() method to find last oneStringTokenizer tokenizer = new StringTokenizer("42 58");while (tokenizer.hasMoreTokens()){ System.out.println(tokenizer.nextToken());}
Programming and Problem Solving With Java 28
Text FilesText file
File that is human-readable with simple tools (type, more, edit, ...)
Variable-length linesEach line terminated by end-of-line markerExample: Java source file
Easy to read and write text filesUse same classes and methods as
System.in and System.inAdvantage of "streams" approach to I/O
Programming and Problem Solving With Java 29
Text Files: The File ClassNeed File object for each file program uses
To defineFile inFile = new File("myFile.dat");
PurposeContains information
about the fileA "placeholder" for
the fileNot the same as
the file data.dat prog.txt input.dat
"myFile.dat"
Computer running program
File variable inFile
Disk of text files
Programming and Problem Solving With Java 30
Text Files: The File ClassMethods in the File class
canRead(): Tells if program can read the file canWrite(): Tells if program can write to the filedelete(): Deletes the fileexists(): Tells if the file is there isDirectory(): Tells if the file is really a directory
name isFile(): Tells if the file is a file (not a directory) length(): Tells the length of the file, in bytes
Programming and Problem Solving With Java 31
Text Files: The File ClassExample of File class
import java.io.*;
class TellIfExists{ public static void main(String[] args) throws java.io.IOException { File myFile = new File("myFile.dat");
if (myFile.exists()) { System.out.println("myFile.dat exists"); } else { System.out.println("myFile.dat does not exist"); } }}
Programming and Problem Solving With Java 32
Text Files: Writing to a FileBefore writing, make sure either
File doesn't exist!outFile.exists()
File exists, and is writeableoutFile.exists() && outFile.canWrite()
Combine conditions!outFile.exists() || outFile.canWrite()
Attach file to a streamFileWriter object: knows how to write stream to a fileWrap FileWriter object in BufferedWriter object for
efficiencyWrap BufferedWriter object in PrintWriter object
Programming and Problem Solving With Java 33
Text Files: Writing to a FileExample code
// Initialize the file variableFile outFile = new File("myFile.dat");
// Make sure that the file either doesn't exist or// we can write to itif (!outFile.exists() || outFile.canWrite()){ // Create an output stream and attach it to the file PrintWriter fileOutStream = new PrintWriter(new BufferedWriter( new FileWriter(outFile)));
// Write to the file ...}else{ // Error: Can't write to the file}
Programming and Problem Solving With Java 34
Text Files: Writing to a FileUse PrintWriter object like System.out
fileOutStream.print("This goes ");fileOutStream.println("to the file");
System.out and fileOutStream are both output streams•System.out is PrintStream object•fileOutStream is PrintWriter object•PrintStream and PrintWriter are almost identical (PrintWriter is newer)
print(), println(), flush() work the sameOnce done writing to the file, close it
fileOutStream.close();
Program does this when it endGood idea to do explicitly, though
Programming and Problem Solving With Java 35
Text Files: Writing to a FileExample
// This program writes a table of squares and// square roots to the file myfile.dat.
import java.io.*;
class WriteSquaresAndSquareRoots{ public static void main(String[] args) throws java.io.IOException { // Initialize the output file variable File outFile = new File("myFile.dat"); if (!outFile.exists() || outFile.canWrite()) { // Create a buffered output stream, wrapped by // PrintWriter, and attach it to the file PrintWriter fileOutStream = new PrintWriter(new BufferedWriter (new FileWriter(outFile)));
// Write the output to the file for (int number = 1; number <= 10; number++) fileOutStream.println(number + "\t" + Math.sqrt(number) + "\t\t" + number * number);
Programming and Problem Solving With Java 36
Text Files: Writing to a FileExample (continued)
// Close the output stream fileOutStream.close(); } else { System.out.println("Problem creating output file "); } System.out.println("Done"); }}
Contents of file1 1.0 12 1.4142135623730951 43 1.7320508075688772 94 2.0 165 2.23606797749979 256 2.449489742783178 367 2.6457513110645907 498 2.8284271247461903 649 3.0 8110 3.1622776601683795 100
Programming and Problem Solving With Java 37
Text Files: Reading from a FileDefine File object
File inFile = new File("myFile.dat");
Before reading, make sure bothFile exists and is readable
inFile.exists() && inFile.canRead()
Attach file to a streamFileReader object: knows how to read stream from a fileWrap FileReader object in BufferedReader object for
efficiencyBufferedReader works on files just like System.in
read(): read a single character, or -1 if EOF readLine(): read a line, or null if EOF
Programming and Problem Solving With Java 38
Text Files: Reading from a FileExample code
// Initialize the file variableFile inFile = new File("myFile.dat");
// Make sure the file can be read fromif (inFile.exists() && inFile.canRead()){ // Create an input stream and attach it to the file BufferedReader fileInStream = new BufferedReader(new FileReader(inFile));
// Read from the file stream the same way as reading // from the keyboard ...}else{ // Error: Can't read from file}
Programming and Problem Solving With Java 39
Text Files: Reading from a FileComplete example: read() method
// Reads a file and displays the number of digits,// upper case letters, lower case letters, and other characters// in the file.
import java.io.*;
class CountLettersDigits{ public static void main(String[] args) throws java.io.IOException { int nextValue, numUpperCase = 0, numLowerCase = 0, numDigits = 0, numOther = 0; char nextChar; String inputFileName;
// Create a buffered input stream and attach it to standard // input BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); // Get input file name from user System.out.print("Enter input file name: "); System.out.flush(); inputFileName = inStream.readLine();
Programming and Problem Solving With Java 40
Text Files: Reading from a FileComplete example (continued)
// Initialize the file variable File inFile = new File(inputFileName);
// Make sure the file can be read from if (inFile.exists() && inFile.canRead()) { // Create an input stream and attach it to the file BufferedReader fileInStream = new BufferedReader(new FileReader(inFile));
Programming and Problem Solving With Java 41
Text Files: Reading from a FileComplete example (continued)
// Read from the file nextValue = fileInStream.read(); while (nextValue != -1) { nextChar = (char) nextValue; if (Character.isDigit(nextChar)) { numDigits++; } else if (Character.isUpperCase(nextChar)) { numUpperCase++; } else if (Character.isLowerCase(nextChar)) { numLowerCase++; } else { numOther++; } nextValue = fileInStream.read(); }
Programming and Problem Solving With Java 42
Text Files: Reading from a FileComplete example (continued)
// Close the stream fileInStream.close();
// Display results System.out.println("Number of digits: " + numDigits); System.out.println("Number of upper case letters: " + numUpperCase); System.out.println("Number of lower case letters: " + numLowerCase); System.out.println("Number of other characters: " + numOther); } else { System.out.println("Can't read " + inputFileName); } }}
Input file: CountCharacters.javaNumber of digits: 7Number of upper case letters: 96Number of lower case letters: 1001Number of other characters: 832
Programming and Problem Solving With Java 43
Text Files: Reading from a FileComplete example: readLine() method
// This program reads a file and displays the file// on the screen, with a line number before each line.
import java.io.*;
class DisplayLinesWithLineNumbers{ public static void main(String[] args) throws java.io.IOException { String inputFileName; String line; int lineNumber = 0;
// Create a buffered input stream and attach it to standard // input BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); System.out.println("--- File Lister ---"); System.out.println();
Programming and Problem Solving With Java 44
Text Files: Reading from a FileComplete example (continued)
// Get file name from user System.out.print("Enter input file name: "); System.out.flush(); inputFileName = inStream.readLine();
// Initialize the input file variable File inFile = new File(inputFileName); if (inFile.exists() && inFile.canRead()) { // Create an input stream and attach it to the file BufferedReader fileInStream = new BufferedReader(new FileReader(inFile)); System.out.println(); System.out.println("--- Contents of file " + inputFileName + "---");
Programming and Problem Solving With Java 45
Text Files: Reading from a FileComplete example (continued)
// Read lines from the input stream, display on screen line = fileInStream.readLine(); while (line != null) { lineNumber++; System.out.println(lineNumber + ":\t" + line); line = fileInStream.readLine(); }
System.out.println("--- End of file ---"); // Close the stream fileInStream.close(); } else { System.out.println("Couldn't open input file " + inputFileName); } }}
--- File Lister ---
Enter input file name: JavaTemplate.java
--- Contents of file JavaTemplate.java---1: class JavaTemplate2: {...--- End of file ---
Programming and Problem Solving With Java 46
Text Files: Reading NumbersSame techniques as reading from keyboard
Get string value from a fileUse NumberFormat object to convert to Number objectConvert Number object primitive type
Example// Reads a file of numbers, square roots, and// squares from myfile.dat and displays the contents on the// screen. Each line of the file should have an integer, the// square root of that integer, and the square of that integer.// (Use the program in Listing 6.15 to create the file.)
import java.io.*;import java.util.StringTokenizer;import java.text.NumberFormat;
Programming and Problem Solving With Java 47
Text Files: Reading NumbersExample (continued)
class ReadSquaresAndSquareRoots{ public static void main(String[] args) throws java.io.IOException, java.text.ParseException { String line; int number, lineNumber = 0; double squareOfNumber, squareRootOfNumber;
// Create a number formatter object NumberFormat aNumberFormatter = NumberFormat.getInstance();
// Initialize the input file variable File inFile = new File("myfile.dat"); if (inFile.exists() && inFile.canRead()) { // Create an input stream and attach it to the file BufferedReader fileInStream = new BufferedReader(new FileReader(inFile));
Programming and Problem Solving With Java 48
Text Files: Reading Numbers Example (continued)
// For each line in the input stream, read an integer and // two doubles (the square of the number and the square // root) and display each value. line = fileInStream.readLine(); while (line != null) { lineNumber++; // Initialize the tokenizer with the last read line StringTokenizer tokenizer = new StringTokenizer(line); // Break the line into an int and two doubles number = aNumberFormatter.parse(tokenizer.nextToken()).intValue(); squareRootOfNumber = aNumberFormatter.parse(tokenizer.nextToken()).doubleValue(); squareOfNumber = aNumberFormatter.parse(tokenizer.nextToken()).doubleValue();
// Dislay the line's contents System.out.println("Line " + lineNumber + " contents:"); System.out.println(" number is " + number); System.out.println(" square root of " + number + " is " + squareRootOfNumber); System.out.println(" square of " + number + " is " + squareOfNumber); // Read the next line line = fileInStream.readLine(); }
Programming and Problem Solving With Java 49
Text Files: Reading from a FileExample (continued)
// Close the stream fileInStream.close(); } else { System.out.println("Couldn't open input file"); } }}
Line 1 contents: number is 1 square root of 1 is 1.0 square of 1 is 1.0Line 2 contents: number is 2 square root of 2 is 1.4142135623730951 square of 2 is 4.0Line 3 contents: number is 3 square root of 3 is 1.7320508075688772 square of 3 is 9.0...Line 10 contents: number is 10 square root of 10 is 3.1622776601683795 square of 10 is 100.0
Programming and Problem Solving With Java 50
Text Files: Reading from a FileExample: Count characters, lines, words
To count characters: increment for each BufferedRead.read()
To count lines: increment for each '\n'Counting words is trickier
Incremental design and developmentGet easy parts written and tested firstAdd other features one at a time to the working
frameworkAdvantage: bug is most likely in most recently added part
of program
Programming and Problem Solving With Java 51
Text Files: Reading from a FileCode for counting characters and lines
// Displays the number of characters and lines in a// text file.
import java.io.*;
class CountCharsLines{ public static void main(String[] args) throws java.io.IOException { String inputFileName; int charCount = 0; int lineCount = 0; int nextValue; char nextChar;
System.out.println("--- Character and line counter ---"); // Create a buffered input stream and attach it to standard // input BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
Programming and Problem Solving With Java 52
Text Files: Reading from a FileCode for counting characters and lines (continued)
System.out.print("Enter file name: "); System.out.flush(); inputFileName = inStream.readLine(); // Initialize the input file variable File inFile = new File(inputFileName); if (inFile.exists() && inFile.canRead()) { // Create an input stream and attach it to the file BufferedReader fileInStream = new BufferedReader(new FileReader(inFile));
while ((nextValue = fileInStream.read()) != -1) { nextChar = (char) nextValue;
charCount++;
if (nextChar == '\n') { lineCount++; } }
Programming and Problem Solving With Java 53
Text Files: Reading from a FileCode for counting characters and lines (continued)
// Close the stream fileInStream.close();
// Display results System.out.println(); System.out.println("Characters in file: " + charCount); System.out.println("Lines in file: " + lineCount); } else { System.out.println("Can't open file" + inputFileName); } }}
--- Character and line counter ---Enter file name: Alice.excerpt.txt
Characters in file: 1127Lines in file: 29
Programming and Problem Solving With Java 54
Text Files: Reading from a FileWord counting
"Word": continguous sequence of characters separated by white space
Add word counting: approach 1Count spacesProblem: may be more than one space between words
Add word counting: approach 2Count transitions from non-word to word (word
beginnings)Must keep track of program state: in a word or not
Programming and Problem Solving With Java 55
Text Files: Reading from a FileCounting characters, lines, words
// Displays the number of characters, lines, and words// in a text file. (This program extends the character and line// counting program; the changed lines are highlighted.)
import java.io.*;
class CountCharsLinesWords{ public static void main(String[] args) throws java.io.IOException { String inputFileName; int charCount = 0; int lineCount = 0;
int wordCount = 0; int nextValue; char nextChar;
boolean inWord = false;
Programming and Problem Solving With Java 56
Text Files: Reading from a FileCounting characters, lines, words (continued)
System.out.println("--- Character, line, and word counter ---"); // Create a buffered input stream and attach it to standard // input BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter file name: "); System.out.flush(); inputFileName = inStream.readLine();
Programming and Problem Solving With Java 57
Text Files: Reading from a FileCounting characters, lines, words (continued)
// Initialize the input file variable File inFile = new File(inputFileName); if (inFile.exists() && inFile.canRead()) { // Create an input stream and attach it to the file BufferedReader fileInStream = new BufferedReader(new FileReader(inFile));
while ((nextValue = fileInStream.read()) != -1) { nextChar = (char) nextValue;
charCount++;
if (nextChar == '\n') { lineCount++; }
else if (Character.isWhitespace(nextChar)) { inWord = false; } else if (!inWord) { inWord = true; wordCount++; }
}
Programming and Problem Solving With Java 58
Text Files: Reading from a FileCounting characters, lines, words (continued)
// Close the stream fileInStream.close();
// Display results System.out.println(); System.out.println("Characters in file: " + charCount); System.out.println("Lines in file: " + lineCount);
System.out.println("Words in file: " + wordCount); } else { System.out.println("Can't open file" + inputFileName); } }}--- Character, line, and word counter ---
Enter file name: Alice.excerpt.txt
Characters in file: 1127Lines in file: 29Words in file: 194
Programming and Problem Solving With Java 59
Text Files: Multiple FilesCan read and write multiple files simultaneously
Define separate File object and stream for eachExample: change lower case letters to upper case
Initialize the input file object If it's OK to read from the input file
•Establish an input stream and attach to input file•Initialize the output file object•If the output file doesn't exist or is writeable
•Establish output stream and attach to output file•Process the streams•Close both streams
•Otherwise, display an error message, close input streamOtherwise, display an error message
Programming and Problem Solving With Java 60
Text Files: Multiple Files// This program copies an existing file to a new// file, changing all lower case characters to upper case and// leaving other characters as they are.
import java.io.*;
class CopyFileToAllUpperCase{ public static void main(String[] args) throws java.io.IOException { int nextValue; // Create a buffered input stream and attach it to standard // input BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); // Display program title System.out.println("--- Copy File to All Upper Case ---"); System.out.println();
// Get file names from user System.out.print("Enter input file name: "); System.out.flush(); String inputFileName = inStream.readLine(); System.out.print("Enter output file name: "); System.out.flush(); String outputFileName = inStream.readLine();
Programming and Problem Solving With Java 61
Text Files: Multiple Files // Open the input file File inFile = new File(inputFileName); if (inFile.exists() && inFile.canRead()) { // Create an input stream and attach it to the file BufferedReader fileInStream = new BufferedReader(new FileReader(inFile));
// Open the output file File outFile = new File(outputFileName); if (!outFile.exists() || outFile.canWrite()) { // Create an output stream and attach it to the file PrintWriter fileOutStream = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
// Read characters from input stream, write each to output // stream until no more characters nextValue = fileInStream.read(); while (nextValue != -1) { fileOutStream.write(Character.toUpperCase((char) nextValue)); nextValue = fileInStream.read(); }
// Close the files fileInStream.close(); fileOutStream.close(); }
Programming and Problem Solving With Java 62
Text Files: Multiple Files else { System.out.println("Problem creating output file " + outputFileName); // Close the input file fileInStream.close(); } } else { System.out.println("Couldn't open input file" + inputFileName); } }}
--- Copy File to All Upper Case ---
Enter input file name: Alice.excerpt.txtEnter output file name: Alice.excerpt.new
THERE WAS A TABLE SET OUT UNDER A TREE IN FRONT OF THE HOUSE,AND THE MARCH HARE AND THE HATTER WERE HAVING TEA AT IT: ADORMOUSE WAS SITTING BETWEEN THEM, FAST ASLEEP, AND THE OTHER TWO...
Contents of Alice.excerpt.new, after program finishes:
Displayed on screen:
Programming and Problem Solving With Java 63
DatabasesMost computer data stored in databases
Database: collection of information stored in computerDatabase management system (DBMS): set of programs
that maintaina database
Programs must go throughDBMS to get to data
WithoutDBMS
WithDBMS
User
User
OperatingSystem
DataApplication
OperatingSystem
DataApplicationDatabase
ManagementSystem
Programming and Problem Solving With Java 64
DatabasesDatabase is more
than just dataDatabase stores
Data Description about
the dataAdvantage
Independence fromprograms
In contrast, Java text file stores just data
Programwith
File Description
OperatingSystem
Filewith
Data only
Programwith
File Description
Programwith
File Description
Program
OperatingSystem
FilewithData
and Description
Program
Program
DatabaseManagement
System
WithoutDBMS
WithDBMS
Programming and Problem Solving With Java 65
DatabasesDatabase systems reduce redundancy
Each piece of information stored onceLess chance of inconsistent dataLess work to update the data -- change it onceSaves storage space
Many programs can share the same informationConcurrency control: part of database system that lets
more than one program use same data at onceQuery system lets users get to data
Ordinary users can use -- don't need programmerCan write and execute queries quickly
Programming and Problem Solving With Java 66
Convert
Convert
Database Design ProcessStart with idea
Purpose of the databaseConceptual model
High-level design Ignore physical issues Most popular: Entity-
relationship (E/R) modelPhysical model
Low-level design Maps conceptual model to a
database system
Idea
ConceptualModel
PhysicalModel
Programming and Problem Solving With Java 67
Database Design: E/R modelEntity-relationship model consists of
Entities: represent real-world objects (people, employees, departments, parts, machines, engines, ...)
Attributes: characteristics of entities (color, weight, size, manager, name, address, part number, ...)
Relationships between entities (employees work for a department, an automobile has an engine, ...)
Entity
Attribute
EntityRelation-ship
Programming and Problem Solving With Java 68
Database Design: E/R modelKinds of relationships
1-1: "one-to-one"
1-N: "one-to-many"
N-N: "many-to-many"
Dept ManagerSupervise1 1
Dept EmployeeWorksin
1 N
Student CourseTakesN N
Programming and Problem Solving With Java 69
Database Design: E/R modelExample
Department
Worksfor
EmployeeHas
degreeEntity name
Managerof
1
1
1
N
1 N
Name
DeptNumber
Name
EmplNumber
Salary JobCode
Education
Salary JobCode Year
DegreeInstitution
Programming and Problem Solving With Java 70
Database ModelsDatabase model: way the database is organizedMajor database models
Hierarchic (old model)Network (old model)Relational (most popular)Object (the future?)
Schema vs. instanceSchema is the layout of the database (like a class in
Java) Instance is the data in the database (like an instance of
an object in Java)
Programming and Problem Solving With Java 71
Database Models: HierarchicThe oldest data modelRecord vs. record type
Record types in schema Records in instance
Record type can have any number of children at most one parent
Links by physical pointersWorks well when data
organized in tree-like structure
"Manufacturing"34
1234"Engineering"
341234
"Lee"345630K8A
"Smith"456730K7A
DepartmentName
DeptNumberManager
EmployeeName
EmpNumberSalary
JobCode
EducationInstitution
DegreeYear
"Accounting"34
1234
"Jones"123430K6A
"ABC High"Certif1984
"XYZ College"BS
1990
Schema Instances
Programming and Problem Solving With Java 72
Database Models: NetworkGeneralizes the
hierarchic model Data organized as graph Record type can have
more than one parentRecord occurrences
Linked in a "chain"Links by physical pointers
"Manufacturing"34
"Engineering"34
"Lee"345630K8A
"Smith"456730K7A
DepartmentName
DeptNumber
EmployeeName
EmpNumberSalary
JobCodeM
anager of
EducationInstitution
DegreeYear
"Accounting"34
"Jones"123430K6A
"ABC High"Certif1984
"XYZ College"BS
1990
Schema Instances
Works for
Has degree
Worksfor
Hasdegree
Managerof
Programming and Problem Solving With Java 73
Database Models: RelationalOrganization by tables
No order to data in tableSchema and instance
Schema is table headings Instance is contents of tables
Links between tables by value Key: identifier attribute for
each row Link by foreign key: key of
another table Physical pointers not used
Department
Name DeptNumber Manager
Accounting 34 1234Engineering 53 3949Manufacturing 21 8493
Employee
Name EmplNumber Salary JobCode DeptNumber
Jones 1234 30K 6A 34Smith 4567 30K 7A 34Lee 3456 30K 8A 34Anders 9876 32K 6B 53Wells 7475 30K 7A 53Mies 3939 29K 8A 21
Education
Institution Degree Year EmplNumber
XYZ College BS 1990 1234ABC High Diploma 1984 1234XYZ College BS 1980 4567GHI University BA 1985 9876PQR Tech Assoc 1994 3939Univ. TUV BS 1985 3456
Programming and Problem Solving With Java 74
Database Models: ObjectObject databases are still new
May be the future of all databasesMore likely, relational and object databases will be used
Based on object-oriented programming languages (Smalltalk, Java, C++)
Database structure is the class structure in a languageVery natural way to store data from OO languageEasier to use than translating to another model
Still many problems to be worked outEfficiency, ability to query easily, reliability, ...
Programming and Problem Solving With Java 75
Databases: N-N RelationshipsCan implement N-N
relationship directly inObject database
Can't in Hierarchic Network Relational
Must translate in these cases
Student
Course
Takes
NN
Student
Takes
N
Taken by
Student-Course
Course
11
N
Programming and Problem Solving With Java 76
Relational Database DesignStart with E/R model
Convert N-N relationships to 2 1-N relationshipsEach entity becomes a relation (table)Each attribute becomes an attribute (column header)For each 1-N relationship
•Put foreign key of "1-side" relation in "N-side" relationFor each 1-1 relationship, either
•Merge the two relations•Treat as 1-N
Next, check the normal form of each relation
Programming and Problem Solving With Java 77
Relational Database DesignNormal form
Indicates possible amount of redundant dataHigher normal form is better (less redundancy)
First normal formEach attribute is atomic (can't divide it)
Second normal formKey may be two or more attributesEach attribute must depend fully on the key (not just part
of it)Third normal form
Attributes depend just on the key attribute
Programming and Problem Solving With Java 78
Database Query LanguagesQuery language
High-level way to get to the data without programmingAllows users to check the data easily
SQL (structured query language)User interface: textLike a programming language (has syntax)Declarative (state what you want, not how to get it)
QBE (query by example)User interface: graphicalVery easy to use (no syntax, just click and drag)Also declarative
Programming and Problem Solving With Java 79
Database Query Languages: SQLQuery 1: list all employees
and their salariesSQL
SELECT Name, SalaryFROM Employee;
Result
Department
Name DeptNumber Manager
Accounting 34 1234Engineering 53 3949Manufacturing 21 8493
Employee
Name EmplNumber Salary JobCode DeptNumber
Jones 1234 30K 6A 34Smith 4567 30K 7A 34Lee 3456 30K 8A 34Anders 9876 32K 6B 53Wells 7475 30K 7A 53Mies 3939 29K 8A 21
Education
Institution Degree Year EmplNumber
XYZ College BS 1990 1234ABC High Diploma 1984 1234XYZ College BS 1980 4567GHI University BA 1985 9876PQR Tech Assoc 1994 3939Univ. TUV BS 1985 3456
Name Salary
Jones 30K
Smith 30K
Lee 30K
Anders 32K
Wells 30K
Mies 29K
Programming and Problem Solving With Java 80
Database Query Languages: SQLQuery 2: list all employees
in dept 34 and their salaries
SQLSELECT Name, SalaryFROM EmployeeWHERE DeptNumber = 34;
Result
Department
Name DeptNumber Manager
Accounting 34 1234Engineering 53 3949Manufacturing 21 8493
Employee
Name EmplNumber Salary JobCode DeptNumber
Jones 1234 30K 6A 34Smith 4567 30K 7A 34Lee 3456 30K 8A 34Anders 9876 32K 6B 53Wells 7475 30K 7A 53Mies 3939 29K 8A 21
Education
Institution Degree Year EmplNumber
XYZ College BS 1990 1234ABC High Diploma 1984 1234XYZ College BS 1980 4567GHI University BA 1985 9876PQR Tech Assoc 1994 3939Univ. TUV BS 1985 3456
Name Salary
Jones 30K
Smith 30K
Lee 30K
Programming and Problem Solving With Java 81
Database Query Languages: SQLQuery 3: list name, dept,
salary of each employeeSQL
SELECT Employee.Name, Salary, Department.NameFROM Employee, DepartmentWHERE Employee.DeptNumber = Department.DeptNumber;
ResultName Salary Name
Jones 30K Accounting
Smith 30K Accounting
Lee 30K Accounting
Anders 32K Engineering
Wells 30K Engineering
Mies 29K Manufacturing
Department
Name DeptNumber Manager
Accounting 34 1234Engineering 53 3949Manufacturing 21 8493
Employee
Name EmplNumber Salary JobCode DeptNumber
Jones 1234 30K 6A 34Smith 4567 30K 7A 34Lee 3456 30K 8A 34Anders 9876 32K 6B 53Wells 7475 30K 7A 53Mies 3939 29K 8A 21
Education
Institution Degree Year EmplNumber
XYZ College BS 1990 1234ABC High Diploma 1984 1234XYZ College BS 1980 4567GHI University BA 1985 9876PQR Tech Assoc 1994 3939Univ. TUV BS 1985 3456
Programming and Problem Solving With Java 82
Database Query Languages: QBEQuery 1: list all employees
and their salariesSolution in Microsoft
Access 97
Department
Name DeptNumber Manager
Accounting 34 1234Engineering 53 3949Manufacturing 21 8493
Employee
Name EmplNumber Salary JobCode DeptNumber
Jones 1234 30K 6A 34Smith 4567 30K 7A 34Lee 3456 30K 8A 34Anders 9876 32K 6B 53Wells 7475 30K 7A 53Mies 3939 29K 8A 21
Education
Institution Degree Year EmplNumber
XYZ College BS 1990 1234ABC High Diploma 1984 1234XYZ College BS 1980 4567GHI University BA 1985 9876PQR Tech Assoc 1994 3939Univ. TUV BS 1985 3456
Programming and Problem Solving With Java 83
Database Query Languages: QBEQuery 2: list all employees in
dept 34 and their salariesSolution in Microsoft Access
97
Department
Name DeptNumber Manager
Accounting 34 1234Engineering 53 3949Manufacturing 21 8493
Employee
Name EmplNumber Salary JobCode DeptNumber
Jones 1234 30K 6A 34Smith 4567 30K 7A 34Lee 3456 30K 8A 34Anders 9876 32K 6B 53Wells 7475 30K 7A 53Mies 3939 29K 8A 21
Education
Institution Degree Year EmplNumber
XYZ College BS 1990 1234ABC High Diploma 1984 1234XYZ College BS 1980 4567GHI University BA 1985 9876PQR Tech Assoc 1994 3939Univ. TUV BS 1985 3456
Programming and Problem Solving With Java 84
Database Query Languages: QBEQuery 3: list name, dept,
salary of each employeeSolution in Microsoft
Access 97
Department
Name DeptNumber Manager
Accounting 34 1234Engineering 53 3949Manufacturing 21 8493
Employee
Name EmplNumber Salary JobCode DeptNumber
Jones 1234 30K 6A 34Smith 4567 30K 7A 34Lee 3456 30K 8A 34Anders 9876 32K 6B 53Wells 7475 30K 7A 53Mies 3939 29K 8A 21
Education
Institution Degree Year EmplNumber
XYZ College BS 1990 1234ABC High Diploma 1984 1234XYZ College BS 1980 4567GHI University BA 1985 9876PQR Tech Assoc 1994 3939Univ. TUV BS 1985 3456