Presentation is loading. Please wait.

Presentation is loading. Please wait.

© Xiaoying Gao, Peter Andreae COMP 102 15:1 Term test Grade Marks No of students “A” range 36 ~45 53 “B” range29.25~35.933 “C” range 22.5~2941 “D” range18-22.412.

Similar presentations


Presentation on theme: "© Xiaoying Gao, Peter Andreae COMP 102 15:1 Term test Grade Marks No of students “A” range 36 ~45 53 “B” range29.25~35.933 “C” range 22.5~2941 “D” range18-22.412."— Presentation transcript:

1 © Xiaoying Gao, Peter Andreae COMP :1 Term test Grade Marks No of students “A” range 36 ~45 53 “B” range29.25~ “C” range 22.5~2941 “D” range “E” range0~1810 Average = 32.4 Total no of students: 142 No of students who sat the test: 128

2 Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington More Files COMP 102 # T2

3 © Xiaoying Gao, Peter Andreae COMP :3 Menu Writing to a file Assignment 5 Choose a file name to open a file Nested loop Admin Term test is handed back Ask questions at labs or tutorials me or talk to me for any mistakes

4 © Xiaoying Gao, Peter Andreae COMP : 4 Testing end of file Unlike 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 second Note: name must be just one token!! James 33 Helen 25 John 73 pondy 19

5 © Xiaoying Gao, Peter Andreae COMP : 5 Writing to a File Open a File Wrap it in a new PrintStream object. 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() : try … catch… File Object

6 © Xiaoying Gao, Peter Andreae COMP : 6 Checking if files exist Can check that file exists before trying to read: Import ecs100.*; import java.util.*; import java.io.* 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);} }

7 © Xiaoying Gao, Peter Andreae COMP : 7 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; }

8 © Xiaoying Gao, Peter Andreae COMP : 8 UIFileChooser So far, we’ve specified which file to open and read or write. eg: File myfile = new File(“input.txt”); How can we allow the user to choose a file ? UIFileChooser class (part of ecs102 library, like UI) MethodWhat it doesReturns open() Opens dialog box; user can select an existing file to open. Returns name of file or null if user cancelled. String open(String title) Same as open(), but with specified title;String save() Opens dialog box; user can select file (possibly new) to save to. Returns name of file, or null if the user cancelled. String save(String title) Same as save(), but with specified title.String

9 © Xiaoying Gao, Peter Andreae COMP : 9 /** 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: open

10 © Xiaoying Gao, Peter Andreae COMP : 10 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);

11 ©Xiaoying Gao, Peter Andreae COMP :11 Where have we been: Elements of Java classes and methods statements expressions, arithmetic, variables and assignments calling methods, passing arguments, using returned values defining methods, parameters, return values types int, double, String, long, boolean CartoonFigure, Butterfly, Scanner, PrintStream, File, … conditional control structures: if ( … ) … else … while ( … ) … boolean expressions, with &&, ||, ! files, Scanner, Printstream, try … catch (…)…, exceptions constructing new objects.

12 ©Xiaoying Gao, Peter Andreae COMP :12 Where have we been Programming and Design techniques specification, design/algorithm, code, debugging design using precise English in comments coding using syntax rules (railway diagrams) using documentation debugging compiler identifies syntax errors testing identifies logic errors. indenting for readability

13 © Xiaoying Gao, Peter Andreae Comp102 16:13 Debugging Techniques Print statements: record progress and state through program public void draw(double left, double top){ Trace.printf("Debug: enter House.draw(%d, %d)\n", left, top); UI.drawRect(left, top, size, size); UI.drawLine(left, top, left+size/2, top-size/2); UI.drawLine(left+size, top, left+size/2, top-size/2); this.drawWindow(left+size/8, top+size*3/8, size/4 ); this.drawWindow(left+size*5/8, top+size*3/8, size/4 ); Trace.printf("Debug: exit House.draw\n"); } public void drawWindow(double left, double top, double sz){ Trace.printf("Debug: enter House.drawWindow(%d, %d, %d)\n", left, top, sz); UI.drawRect(left, top, sz, sz); UI.drawLine(left, top+sz/2, left+sz, top+sz/2); UI.drawLine(left+sz/2, top, left+sz/2, top+sz); Trace.printf("Debug: exit House.drawWindow\n"); }

14 © Xiaoying Gao, Peter Andreae Comp102 16:14 Debugging Techniques Print statements: record progress and state through program public void printCourse(){ Trace.println("Debug: entering printCourse"); String targetCode = UI.AskString("Enter course code: ").toUpperCase(); UI.printf("Exam room data for %s:\n", targetCode); try{ Scanner fileScan = new Scanner(new File("examdata.txt")); while (fileScan.hasNext()){ String code = fileScan.next(); String restOfLine = fileScan.nextLine(); Trace.printf("Debug: comparing %s to %s\n", code, targetCode); if (code.equals(targetCode)) { UI.println(code+"\t"+restOfLine); } fileScan.close(); }catch (IOException e){UI.println("File reading failed: "+e);} Trace.println("Debug: exiting printCourse"); }

15 © Xiaoying Gao, Peter Andreae Comp102 16:15 Debugging: Use BlueJ debugger Lets you step through your code. Compile your code place stop signs in left margin run program In debugger window Step ⇒ perform the next statement Step Into ⇒ step inside the method calls in the next statement Continue ⇒ run until you hit another stop sign Terminate ⇒ stop your program You can double click on local variables to look inside them.

16 © Xiaoying Gao, Peter Andreae COMP :16 Nested loops public void nestLoops(){ int rows =4; int cols =3; int r =0; int c =0; while (r < rows){ c=0; while(c < cols){ UI.printf(" (%d, %d) ", r, c); c++; } UI.println(); r++; } } (Debugger window: step by step)

17 © Xiaoying Gao, Peter Andreae COMP :17 public void drawCircles() { int top = 100; int left =100; int diam =20; int x = left; int y = top; int rows = 4; int cols = 3; int r = 0;int c = 0; while (r < rows){ c = 0; x = left; while ( c < cols ) { UI.fillOval(x, y, diam, diam); c++; x = x + diam; } r++; y = y + diam; } Nested loops

18 © Peter Andreae COMP102 11:18 Nested loops public void drawCircles(int rows, int cols) { int row = 0; while (row < rows) { int diam = 20; col = 0; while ( col < cols ) { int x = 50 + col*diam; int y = 20 + row*diam; UI.fillOval(x, y, diam, diam); col++; } row++; }

19 © Xiaoying Gao, Peter Andreae Comp102 16:19 The main method How can you run a program without BlueJ? Option1: Type javac CurrencyConverter.java java CurrencyConverter in a command window (“shell” on unix) (must change to the appropriate directory first.)

20 © Xiaoying Gao, Peter Andreae Comp102 16:20 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.

21 © Xiaoying Gao, Peter Andreae Comp102 16:21 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(…)

22 © Xiaoying Gao, Peter Andreae Comp102 16:22 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(); }

23 © Xiaoying Gao, Peter Andreae Comp102 16:23 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

24 © Xiaoying Gao, Peter Andreae Comp102 16:24 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.

25 © Xiaoying Gao, Peter Andreae Comp102 16:25 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 "© Xiaoying Gao, Peter Andreae COMP 102 15:1 Term test Grade Marks No of students “A” range 36 ~45 53 “B” range29.25~35.933 “C” range 22.5~2941 “D” range18-22.412."

Similar presentations


Ads by Google