© 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.

Slides:



Advertisements
Similar presentations
Chapter 8 Improving the User Interface
Advertisements

MiniDraw Testing COMP 102 # T1
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Creating and using Objects.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Methods COMP.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Design, Debugging & Introduction.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Java Programs COMP 102 #3.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Review COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Program Elements and Syntax.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Conditionals.
© Xiaoying Gao, Peter Andreae Class, method, statements COMP 102 #3 2014T2 Xiaoying Sharon Gao Computer Science Victoria University of Wellington.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington While loops and the UI API.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Create Objects,
©Xiaoying Gao, Peter Andreae First Java Program COMP 102 #2 2014T2 Xiaoying Sharon Gao Computer Science Victoria University of Wellington.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
First Java Program COMP 102 #2 2015T2 Xiaoying Sharon Gao Computer Science Victoria University of Wellington.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Call a Method,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Patterns with.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading:
2011-T1 Lecture 13 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Topic 19 file input, line based Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Files COMP 102.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Conditionals.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington More Interfaces.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Exercise, printf,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More Event-driven Input TextFields,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Classes, Objects, Fields,
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Creating Objects.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Classes and.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Fields, Constructors.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Creating Objects.
Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading:
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Classes and.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Java Programs COMP 102 #3.
© Xiaoying Gao, Peter Andreae Variables, Constants, UI methods COMP 102 #4 2014T2 Xiaoying Sharon Gao Computer Science Victoria University of Wellington.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Programs with Choice Booleans,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
2011-T1 Lecture 12 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops.
© Peter Andreae Java Programs COMP 102 # T1 Peter Andreae Computer Science Victoria University of Wellington.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Methods with.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Dealing with Files COMP 102.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More Event-driven Input COMP.
Program with two classes COMP 102 # T2
Files The UI text pane window is transient:
Chapter 7 User-Defined Methods.
Writing to a File Open a File Wrap it in a new PrintStream object.
Chapter 2: Java Fundamentals cont’d
Presentation transcript:

© 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

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

© 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

© 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

© 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

© 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);} }

© 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; }

© 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

© 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

© 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);

©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.

©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

© 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"); }

© 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"); }

© 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.

© 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)

© 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

© 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++; }

© 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.)

© 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.

© 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(…)

© 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(); }

© 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

© 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.

© 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