Presentation is loading. Please wait.

Presentation is loading. Please wait.

2011-T1 Lecture 13 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.

Similar presentations


Presentation on theme: "2011-T1 Lecture 13 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda."— Presentation transcript:

1 2011-T1 Lecture 13 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda More Files and main Method

2 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

3 3 Passing an open scanner  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(); // throws result away ! count = count+1; } return count; }

4 4 Files: An overview My Program : int a =.nextInt(); : } My Program : int a =.nextInt(); : } A real file: “myfile.txt” File (object) Scanner (object) next(); println(); PrintStream (object)

5 5 Writing to a File  Open a File  Wrap it in a new PrintStream  Call print, println, or printf on it.  Close the file : 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() : File Object

6 6 Checking if files exist before reading  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() ); } out.close(); sc.close(); } catch (IOException e) {UI.printf(“File failure %s\n”, e);} } num will start from 0 and go up to total number of lines (including blank lines) in the infile -1

7 7 UIFileChooser  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... MethodWhat it doesReturns 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 file (possibly new) to save to. Returns a string that is the name of the file, or null if the user cancelled. String 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

8 8 Using UIFileChooser methods: open /** 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.

9 9 Using UIFileChooser methods: save /** 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);

10 10 The main method  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.)

11 11 The main method (contd.) 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.

12 12 The main method 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(…)

13 13 CurrencyConverter with main /** 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(); }

14 14 public static void main(String[ ] args){  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

15 15 Static vs non-static methods  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.

16 16 Learning from Assignments  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


Download ppt "2011-T1 Lecture 13 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda."

Similar presentations


Ads by Google