COMP 102 #4 6 Mar 2006
Download
Report
Transcript COMP 102 #4 6 Mar 2006
COMP 102
More Files and main Method
Rashina Hoda and Peter Andreae
2011-T1 Lecture 13
Rashina Hoda
School of Engineering and Computer Science, Victoria University of Wellington
2
RECAP-TODAY
RECAP
Next methods
Reading from Files
TODAY
Writing to Files, UIFileChooser
main Method
Administrivia:
Some common issues on forum: string comparison and while loops
Assignment#4 due tomorrow
Passing an open scanner
3
First method:
Just opens and closes the file
public void countTokensInFile(String fname){
try {
Scanner sc = new Scanner (new File(fname));
UI.printf(“%s has %d tokens\n”, fname, this.countT(sc));
sc.close();
} catch (Exception e) {UI.printf(“File failure %s\n”, e);}
}
Second Method: Just reads from the file and counts
public int countT (Scanner scan){
int count = 0;
while (scan.hasNext()) {
scan.next();
count = count+1;
}
return count;
}
// throws result away !
4
Files: An overview
A real file: “myfile.txt”
My Program
:
int a =
<ob>.nextInt();
:
}
next();
Scanner
(object)
File
(object)
println();
PrintStream
(object)
Writing to a File
5
Open a File
Wrap it in a new PrintStream
Call print, println, or printf on it.
Close the file
File Object
:
PrintStream out = new PrintStream(new File("Square-table.txt"));
int n=1;
out.println("Number\tSquare");
while ( n <= 1000 ) {
out.printf("%6d\t%8d\n", n, n*n);
n = n+1;
}
out.close()
:
Checking if files exist before reading
6
Can check that file exists before trying to read:
/** Make a copy of a file with line numbers */
public void lineNumber(String fname){
File infile = new File(fname);
if (infile.exists()) {
File outfile = new File(“numbered-” +fname);
try {
PrintStream out = new PrintStream(outfile);
Scanner sc = new Scanner ( infile );
int num = 0;
while (sc.hasNextLine()) {
out.println((num++) + “: ” + sc.nextLine() );
}
num will start from 0 and go up to total number
out.close();
of lines (including blank lines) in the infile -1
sc.close();
} catch (IOException e) {UI.printf(“File failure %s\n”, e);}
}
}
UIFileChooser
7
So far, we’ve spelled out which file to open and read or write on. Example:
File myfile = new File(“input.txt”);
How can we allow the user to choose a file? UIFileChooser to the rescue...
Method
What it does
Returns
open()
Opens a file chooser dialog box to allow the user to select
an existing file to open. Returns name of file or null if user
cancelled.
String
open(String title) Opens a file chooser dialog box with a specified title.
Allows the user to select an existing file to open. Returns a
string that is the name of the file, or null if the user
cancelled.
String
save()
Opens a file chooser dialog box to allow the user to select a String
file (possibly new) to save to. Returns a string that is the
name of the file, or null if the user cancelled.
save(String title)
Opens a file chooser dialog box with a specified title.
Allows the user to select a file (possibly new) to save to.
Returns a string that is the name of the file, or null if the user
cancelled.
String
Using UIFileChooser methods: open
8
/** allow user to choose and open an existing file*/
String filename = UIFileChooser.open();
File myfile = new File(filename);
Scanner scan = new Scanner(myfile);
OR
Scanner scan = new Scanner(new File(UIFileChooser.open()));
/** allow user to choose and open an existing file, specifies a title for dialog box*/
File myfile = new File(UIFileChooser.open(“Choose a file to copy”));
Scanner scan = new Scanner(myfile);
Two “open” methods in one class?
Overloading: two methods in the same class can have the same name
as long as they have different parameters.
Using UIFileChooser methods: save
9
/** allow user to choose and save to a (new/existing) file*/
String filename = UIFileChooser.save();
File myfile = new File(filename);
PrintStream ps = new PrintStream(myfile);
OR
PrintStream ps = new PrintStream(new File(UIFileChooser.save()));
/** allow user to choose and save to a (new/existing) file, specifies a title for dialog
box*/
File myfile = new File(UIFileChooser.save(“File to save data in”));
PrintStream ps = new PrintStream(myfile);
The main method
10
How can you run a program without BlueJ?
Option1: Type
java CurrencyConverter
in a command window (“shell” on unix)
(must change to the appropriate directory first.)
The main method (contd.)
11
Option 2:
Construct an executable jar file using BlueJ
Project -> Create Jar File
You must specify the main class (in case there are several classes)
You must include the user libraries (e.g. comp102.jar)
Run the jar file (by clicking on it)
Java will “run” the class file.
The main method
12
PROBLEM: what method will java call?
Need a method that is called when the program is started:
Java looks for a special method in the class called main.
If main exists, java will call it.
Typically, main will construct an object and call method(s) on it.
PROBLEM: what object will it call main on?
main is a “static” method:
called on the Class, not on an object.
CurrencyConverter.main(…)
not
curConv1.main(…)
CurrencyConverter with main
13
/** Converts between NZ and foreign currencies */
public class CurrencyConverter {
/** prompts user for $NZ and currency, and prints conversion*/
public void convertMoney ( ){
……
}
/** converts a $NZ amount */
public double computeForeign (double amt, String currency ){
……
}
/** main method */
public static void main(String[ ] args){
CurrencyConverter cc = new CurrencyConverter();
cc.convertMoney();
}
}
public static void main(String[ ] args){
14
Must be public
so it can be called from outside the class
Must be static
so it can be called on the class,
before any objects have been constructed
> java CurrencyConverter
Must have one parameter of type String[ ]
the value will be an array of all the “command line arguments”
> java TTPrinter 2007-timetable.csv -html -out 2007-byslot.html
Typical main
constructs an object of the class and
calls a method on it
Static vs non-static methods
15
The textbook (ch 1 – 3) only used the main method;
The lectures used ordinary methods, but not main
Why?
If you don’t have BlueJ, you can’t run a program without main
(except by using applets, which are more complicated)
⇒ Textbook used main
With BlueJ, you can run individual methods in a program
simpler methods
clearer understanding of objects and methods.
good for testing programs
⇒ This course won’t use main much,
and will always be minimal.
Learning from Assignments
16
Start planning early
Work on the Core parts first
Work out the steps the computer needs to take to solve
the problem before writing the code.
Look at the lecture notes and text book for similar examples
Read the Java Documentation!
Don’t program “by trail and error” — if there is an error,
work out why, don’t just guess and try changing at random
Use the BlueJ “stop signs” and “stepping” tools
to work out what went wrong – ask tutors how
Don’t get hung up on the graphics
Go to the tutorials