Upload
charla-lewis
View
219
Download
0
Embed Size (px)
DESCRIPTION
© Peter Andreae COMP : 3 Designing loops Is the number of steps determined at the beginning? int i = 0;int i = 1; while ( i < number) {while ( i
Citation preview
Peter AndreaeComputer Science
Victoria University of Wellington
Copyright: Peter Andreae, Victoria University of Wellington
Dealing with FilesCOMP 102 # 13 2013
© Peter Andreae
COMP 102 13: 2
Menu• Guidelines for designing loops• Files• Scanners• Examples of methods with loops to process files.Reading:• L-D-C:
AdministrationDid you miss the test???Flu shots: free for students. see details on the Forum.
© Peter Andreae
COMP 102 13: 3
Designing loopsIs the number of steps determined at the beginning?
int i = 0;int i = 1;while ( i < number) { while ( i <= number) {
do actions ⟩ do actions ⟩i = i + 1; i++;
} }• Note, can count from 0 or from 1!
Otherwise⟨intialise ⟩while ( ⟨condition-to-do it again ⟩ ) {
⟨body ⟩⟨increment ⟩
}
Shorthand for i = i+1
© Peter Andreae
COMP 102 13: 4
Designing loopsDoes exiting the loop depend on the actions?
if so orset up for the test while ( true ) {while ( test ) { set up for the test
do actions if ( exit-test ) { set up for the next test break;
} }do actions
}• Write out the steps for a couple of iterations
• including the tests to determine when to quit/keep going• Identify the section that is repeated
• preferably starting with the test• Wrap it with a while ( ) { }• Identify the condition for repeating.
© Peter Andreae
COMP 102 13: 5Nested loops: while inside while
public void drawCircles(int rows, int cols) {int diam = 20;int row = 0;while (row < rows) {
int y = 20 +row*diam;int col = 0;while ( col < cols ) {
int x = 50 + col*diam;UI.fillOval(x, y, diam, diam);col = col + 1;
}row = row + 1;
}}
© Peter Andreae
COMP 102 13: 6
Files• The UI text pane window is transient:
• Typing large amounts of input into the text pane is a pain!
• It would be nice to be able to save the output of the program easily.
• Large amounts of text belong in files• How can you write to a file?• How can you read from a file?
• Easy!• Files behave very like the UI text pane:• next, nextInt etc read from a file, (via a Scanner object)
• print, println, printf write to a file (via a PrintStream object)
© Peter Andreae
COMP 102 13: 7
Files: An overview
My Program :int a =??.nextInt(); :??.println(a*5); }
Enter numbers: 40 60 30 50 done
UI Window
UI.nextInt();
UI.println();A real file: “myfile.txt”
File object
Scannerobject
next();
println();PrintStre
amobject
© Peter Andreae
COMP 102 13: 8
Scanner• Scanner: a class in the java that allows a program to
read user input from a source (console, a file, a String, …)
• New concept? Not really!• UI.next() and other next methods are actually a
Scanner working in the background
while(UI.hasNextInt()){double amt = UI.nextDouble()
}
• Most UI next methods work same as Scanner next methods, but a very few subtle differences…see Java documentation
while(scan.hasNextInt()){ double amt = scan.nextDouble();}
Scanner scan = new Scanner(myfile);
© Peter Andreae
COMP 102 13: 9
Reading using Scanner:/** Read lines from a file and print them to UI text pane. */
public void readFile(){File myfile = new File(“input.txt”);Scanner scan = new Scanner(myfile);UI.println(“----------- input.txt --------------”); while (scan.hasNext()){
String line= scan.nextLine();UI.println(line);
}UI.println(“----------- end of input.txt --------------”);
}
• Almost right, but compiler complains!!!• Dealing with files may “raise exceptions”
© Peter Andreae
COMP 102 13: 10
Files: handling exceptionsIf a piece of code might raise an exception:
• Have to enclose it in a try {
… } catch (IOException e) { … }
public void readFile(){File myfile = new File(“input.txt”);try {
Scanner scan = new Scanner(myfile);while (scan.hasNext()){
String line = scan.nextLine();UI.println(line);
}UI.println(“----------- end of input.txt --------------”);
} catch (IOException e) { UI.println(“File failure: ” + e); }
what to do
what to do if it goes wrong
© Peter Andreae
COMP 102 13: 11
Reading from files: example 2/** Finds oldest person in file of ages and names. */public void printOldest(){
try {Scanner scan = new Scanner(new File(“names.txt"));String oldest = "";int maxAge = 0; while (scan.hasNextInt()){
int age = scan.nextInt();String name = scan.nextLine();if (age > maxAge) {
maxAge = age;oldest = name;
}} UI.printf(“Oldest is %s (%d)%n”, oldest, maxAge);
} catch (IOException e) { UI.printf(“File failure: %s%n”, e); }}
no need to prompt user!
33 James Bond25 Helen Clerk73 John F Quay19 pondy
Copes with multi-token names
© Peter Andreae
COMP 102 13: 12
Testing end of fileUnlike UI text pane, can test for end of file:
/** Finds oldest person in file of names and ages. */public void printOldest(){
try {Scanner scan = new Scanner(new File(“names.txt"));String oldest = “”;int maxAge = 0; while (scan.hasNext()){
String name = scan.next();int age = scan.nextInt();if (age > maxAge) {
maxAge = age;oldest = name;
}}UI.println(“Oldest is %s (%d)%n”, oldest, maxAge);
} catch (IOException e) { UI.printf(“File failure: %s%n”, e); }}
False when at end of file
name first; age secondNote: name must be just one token!!
James 33 Helen 25 John73 pondy 19
© Peter Andreae
COMP 102 13: 13
A common simple pattern• File with one entity per line,
described by multiple values:
while (sc.hasNext() ){String type = sc.next();double cost = sc.nextDouble();int wheels = sc.nextInt();String colour = sc.next();String make = sc.next()if (wheels > 4) {
….}else {
…}
}
bicycle 1025 2 green Gianttruck 120000 18 black Isuzucar 26495 4 red Toyota…
Read all the valuesinto variables
process the values inthe variables