Download Lecture 8

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
Lecture 8
Case Study: Savings Account Interest
Problem. You open a savings account with a specified amount of money;
the bank will pay 1.5% interest each quarter if your deposit is below 10,000
pounds and 2% otherwise. You plan to make no deposit or withdrawals, but
you want to see what each quarterly balance, including interest, will be over
a given period of time.
Loops: recap + example.
Files: abstracting from a specific device.
Streams and Tokens.
Examples.
Material from the second half of Holmes Chapter 4.
1
3
How do you add up a sequence of numbers?
Analysis. The interest for one quarter of a year, given a lump sum of
pounds and an interest rate is
for ( i=0; i<k; i++) {
input next n;
sum = sum + n;
}
do {
input next n;
sum = sum + n;
} while (n > 0);
n = 1;
while (n > 0) {
input next n;
sum = sum + n;
}
... but notice the subtle differences between the three. The next is a slightly
dirtier way of using a for loop to simulate a while.
Before the interest for the next quarter is computed must be redefined as
. The length of the investment is given as input as an integer.
for ( n=1; n>0; ) {
input next n;
sum = sum + n;
}
2
4
// chap_4\Ex_9.java
// program to calculate the accumulated interest payable on a savings
// account
import java.io.*;
class Ex_9 {
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
Pseudo-code
1.
2.
3.
4.
5.
6.
7.
input balance and term (in number of years)
output headings
calculate the number of quarters
for every quarter in the term
calculate interest
calculate balance
output quarter year, interest and balance
public static void main(String[] args) throws IOException {
final float QUARTERLY_RATE_LOW = 0.015f;
final float QUARTERLY_RATE_HIGH = 0.02f;
float balance, interest;
int term, lastQuarter;
boolean high = false;
System.out.print("Input initial balance ");
balance = new Float(keyboard.readLine()).floatValue();
System.out.print("Input length of investment in years ");
term = new Integer(keyboard.readLine()).intValue();
System.out.println("\nquarter\tinterest\tbalance\n");
lastQuarter = 4 * term;
5
6-1
for (int q = 1; q <= lastQuarter; q++) {
if (balance > 10000) {
interest = balance * QUARTERLY_RATE_HIGH;
if (!high) {
System.out.println("Start of high interest regime!");
high = true;
}
}
else
interest = balance * QUARTERLY_RATE_LOW;
balance = balance + interest;
System.out.println(q + "\t" + interest + "\t" + balance);
}
Data dictionary.
final float QUARTERLY_RATE_LOW = 0.015f;
final float QUARTERLY_RATE_HIGH = 0.02f;
float balance;
float interest;
int term;
int lastQuarter;
}
}
Layout. We want to print a number of lines each containing the newly
produced interest and the current balance.
6
6-2
[michele@michele JAVA]\$ java Ex_9
Input initial balance 9000
Input length of investment in years 4
quarter interest
File
[A. Tanenbaum] A file consists of a sequence of bytes written to
an I/O device such as a disk, a CD, a printer.
balance
1
135.0
9135.0
2
137.025
9272.025
3
139.08038
9411.105
4
141.16658
9552.272
5
143.28409
9695.557
6
145.43335
9840.99
7
147.61485
9988.605
8
149.82909
10138.435
Start of high interest regime!
9
202.76869
10341.203
10
206.82405
10548.027
11
210.96054
10758.988
12
215.17976
10974.168
13
219.48335
11193.651
14
223.87302
11417.524
15
228.35048
11645.875
16
232.9175
11878.793
Example. Your Java programs are stored as text files.
Getting into the jargon: variables are declared, files are opened!
FileReader
Physical
File
Your Program
FileReader file = new FileReader("/chap 4/data.txt");
But that’s not all!!
8
6-3
Buffering
FileReader
BufferedReader
More General Input and Output
I/O so far: keyboard and (Holmes) screen.
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
static PrintWriter screen = new PrintWriter(System.out, true);
I/O might be from different “places”: the program might receive data from
a text file or save data to a text file.
How is this handled in Java? and (FIRST) What is a file?
Physical
Your Program
File
BufferReader inputFile = new BufferReader(file);
By doing this we abstract further from the physical details and provide a
mechanism for treating, say, keyboard input in the same way as input
coming from a file.
In practice this gives us more “things” (or methods) that we can do with a
file.
How to close a file (buffered reader).
inputFile.close();
After this method the relationship between inputFile and file is lost.
7
9
// chap_4\Ex_6
// program to read data from a file and display it on the screen
import java.io.*;
class Ex_6 {
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
FileReader file
= new FileReader("data.txt");
BufferedReader inputFile = new BufferedReader(file);
String name;
float price;
// chap_4\Ex_7
// program to read data from a file, modify the information
// and write the information back to a different text file
import java.io.*;
class Ex_7 {
public static void main(String[] args) throws IOException {
final float RATE_OF_INFLATION = 0.025f;
FileReader file1
= new FileReader("data.txt");
BufferedReader inputFile = new BufferedReader(file1);
FileWriter file2
= new FileWriter("results.txt");
PrintWriter outputFile
= new PrintWriter(file2);
String name;
float price;
price = new Float(inputFile.readLine()).floatValue();
while (price != 0) {
price = price + (price * RATE_OF_INFLATION);
name = inputFile.readLine();
outputFile.println(price + " " + name);
price = new Float(inputFile.readLine()).floatValue();
}
price = new Float(inputFile.readLine()).floatValue();
while (price != 0) {
name = inputFile.readLine();
System.out.println(price + "\t"+ name);
price = new Float(inputFile.readLine()).floatValue();
}
inputFile.close();
inputFile.close();
outputFile.close();
}
}
}
}
9-1
Food for Thought.
10-1
Tokenizing
1. Write a program that copies the content of a text file into another.
(Assume that both files exist in your current directory).
(Hints: see example further on).
Java offers other features for dealing with text files. We need to make a
little diversion first!
Strings of text handled by a program my have some structure.
2. Write a program that merges the contents of two text files into a third
one, interleaving lines from one file with lines from the other. (Assume
that all files exist in your current directory).
The following example shows how the content of a file can be read,
modified and copied in another file. Note that the output file is rewritten
every time the program is started!
10
String inputData = "First 124
Second 9012\n";
An object in the StringTokenizer class is an entity that is capable of
breaking strings into tokens. In our Factory metaphor, it is like a worker
that gets a string from a moving belt and chops it into pieces, giving the
pieces on request, one after the other. Once the pieces have been used once
they are “lost”.
11
Class Definition: StringTokenizer
// Constructors (used in declarations)
public StringTokenizer (String str);
Constructs a string tokenizer for the specified string.
Delimiters are "\t\n\r\f".
// Simple program to demostrate the use of a StringTokenizer
//
What is this program actually doing??
import java.io.*;
import java.util.*;
class StringTok {
static BufferedReader keyboard = new
BufferedReader ( new InputStreamReader(System.in) );
public static void main (String[] args) throws IOException {
String s;
StringTokenizer data;
public StringTokenizer (String str, String delim);
Constructs a string tokenizer for the specified string.
User defined delimiters.
public StringTokenizer (String str, String delim, boolean retTok);
Constructs a string tokenizer for the specified string.
User defined delimiters.
If the returnTokens flag is true, then the delimiters are
also returned as tokens (each delimiter returned as a string
of length one. If the flag is false, the delimiter characters
are skipped.
System.out.println("Waiting for your input ... ");
s = keyboard.readLine();
data = new StringTokenizer ( s );
System.out.println( new Integer ( data.nextToken() ).intValue() +
new Integer ( data.nextToken() ).intValue() );
System.out.println( data.countTokens() +
"Tokens still available to the Tokenizer!" );
}
}
12
13-1
Methods
// Methods (services provided by variables/objects in the class)
public boolean hasMoreTokens ();
Tests if there are more tokens available from this
tokenizer’s string.
public String nextToken ();
public String nextToken (String delim);
Methods for reading the next token to a string. The
specification of the delimiter overrides any previous setting.
Now then ...
Text files are just a sequence of lines, each line being a string!
String tokenizers can be applied to these strings!
Here comes an example!
public int countTokens ();
Calculates the number of times that this tokenizer’s
nextToken method can be called before it generates an error.
13
14
// chap_4\Ex_8.java
// program to demonstrate how a string of text can be tokenized
// into single words that are separated by white space characters
import java.io.*;
import java.util.*;
class Ex_8 {
public static void main(String[] args) throws IOException {
FileReader file
= new FileReader("passage.txt");
BufferedReader inputFile = new BufferedReader(file);
StringTokenizer data;
int numberOfTokens, numberOfWords = 0, words;
data = new StringTokenizer(inputFile.readLine());
numberOfTokens = data.countTokens();
while (numberOfTokens !=0) {
for ( words=1; words <= numberOfTokens; words++ )
System.out.print(data.nextToken() + " ");
System.out.println();
numberOfWords = numberOfWords + numberOfTokens;
data = new StringTokenizer(inputFile.readLine());
numberOfTokens = data.countTokens();
}
System.out.println("There are "+numberOfWords+" words in the text.");
}
}
14-1
Tutorial
1. Write a program for multiplying two integers and in the style of the
“trivial” adder presented this morning (the program should repeatedly add to
itself and decrement the second number). Of course the code performing the
addition should be the one given above (you should only use the increment and
decrement operators).
2. Write a program using while loops to output the arithmetic mean of a
sequence of positive integers. (For instance if the input is 12, 7, 12, 10, 9, then
the result should be 10.00). [You may then rewrite it with for loops instead]
3. (A real “mind-cracker”) Write a program for sorting the lines of a text file.
For this exercise it is very important that you first think “on paper” to the algorithm you
want to use. Also
you may assume that the file contains one number (as a sequence of characters) per
line and that the numbers are integers;
alternatively (harder) you can order the lines of the file in lexicographic order using
the compareTo method in the String class.
the program will need to use additional files for copying purposes.
15