Introduction to Computer Program Design COMP 102 Sharon

  • Slides: 128
Download presentation
Introduction to Computer Program Design COMP 102 Sharon Gao & 2019 T 1 .

Introduction to Computer Program Design COMP 102 Sharon Gao & 2019 T 1 . Peter Andreae ( “Pondy” ) Computer Science Victoria University of Wellington Note: 10 -11 lecture repeated at 12 -1, same room © Peter Andreae

COMP 102: 2 Menu: • Welcome • Introductions • What is COMP 102 about?

COMP 102: 2 Menu: • Welcome • Introductions • What is COMP 102 about? • Where does COMP 102 fit in your degree? • Course organisation • What to do NOW! Admin: • Course Outline © Peter Andreae

COMP 102: 3 The COMP 102 Team Organiser Xiaoying Gao (Sharon) Office: CO 339

COMP 102: 3 The COMP 102 Team Organiser Xiaoying Gao (Sharon) Office: CO 339 xgao@ecs. vuw. ac. nz (Overall course management) Lecturer Office hours: Peter Andreae (Pondy) Office: CO 336 pondy@ecs. vuw. ac. nz Office hours: Mon, Thu 1: 15 -2: 00 112 Lecturer David Streader Office: CO 260 dtsr@ecs. vuw. ac. nz Senior Tutor Zarinah Amin Office: CO 252 Zarinah. Amin@ecs. vuw. ac. nz (Admin issues regarding labs) Programmer Dr. Monique Damito Tutors Range of Undergraduates and Graduates School Office (for forgotten passwords) Students You! email to report problems: bugs@ecs. vuw. ac. nz CO 358 © Peter Andreae

What is the course about? COMP 102: 4 • COMP 102 is about learning

What is the course about? COMP 102: 4 • COMP 102 is about learning the language and the ways of thinking required for building the software that underlies our digital world. • Building software means writing programs: writing the instructions to make a computer behave in the way we want it to. • In COMP 102, you will design and write lots of little programs for lots of tasks. • Give you a new set of mental tools for addressing problems • • Different way of thinking from most disciplines Creative, Very precise, Dealing with abstraction and complexity, . © Peter Andreae

COMP 102: 6 Essential Info: Lectures • Lectures: Two streams: • • Mon 10

COMP 102: 6 Essential Info: Lectures • Lectures: Two streams: • • Mon 10 -11, Tues 10 -11, Fri 2 -3 Mon 12 -1, Tues 12 -1, Thu 12 -1 Same content. You can mix and match, as long as there's room • easy to switch to those lectures if you choose Tue Wed Thu LECT A LECT B 112 lect Fri 9 10 11 12 • COMP 112 lectures at same time as second stream of COMP 102. Mon 1 2 LECT A 3 4 5 • Information: • ecs. victoria. ac. nz/Courses/COMP 102_2018 T 1, also accessible via Blackboard © Peter Andreae

COMP 102 vs COMP 112: COMP 102: 7 Two courses taught together as different

COMP 102 vs COMP 112: COMP 102: 7 Two courses taught together as different streams within a combined course. • Both courses lead to COMP 103 • Same assessment • Easy to switch between the streams – • just choose the lectures that work best for you, COMP 102: • • Designed for students who have not done any programming Three lectures/week on programming in Java Goes slower, designed for beginning programmers If you have done some programming, that will obviously help COMP 112: • • Designed for students who have done NCEA level 3 programming standards, or equivalent. Two lectures/week on programming in Java One lecture/week range of topics in Computer Science (not on the test/exam) Goes faster, covers wider range of issues. © Peter Andreae

COMP 102: 8 Essential Info: Labs and Assignments • Labs: Two 1 hr Labs

COMP 102: 8 Essential Info: Labs and Assignments • Labs: Two 1 hr Labs per week: • Pick one TL lab (Mon/Tues) • Pick one AL lab (Thu/Fri) • (Learning to use the lab systems) • First assignment and "real" labs: • next week: Mon/Tues and Thu/Fri Tue LECT A Wed Thu Fri 9 10 • First lab starts this Thursday! Mon 11 Lab AL 5 Lab AL 2 12 LECT B 1 Lab TL 5 2 Lab TL 6 3 Lab TL 7 4 Lab TL 8 LECT B Lab AL 6 Lab AL 7 Lab AL 3 LECT A Lab AL 8 Lab AL 4 5 Labs in CO 219/238 (next to each other) Sign for labs at https: //student-sa. victoria. ac. nz © Peter Andreae

What kind of course is it? COMP 102: 10 • About designing and building

What kind of course is it? COMP 102: 10 • About designing and building software. • Not about using computers and applications software. • Not an “easy credits” course for most people • Involves higher level thinking skills than many students expect • Women students do as well or better than men students. • Key factors for success are • • • problem solving, not memory logical/abstract thinking, attention to detail being able to think about your own thinking processes not getting behind • Takes time! plan on around 10 hours / week • Practical work is critical © Peter Andreae

Background needed for COMP 102: 11 • We assume you have used a computer

Background needed for COMP 102: 11 • We assume you have used a computer • We do NOT assume you have done any programming • If you haven’t, This course is for you! • don’t worry about, or be intimidated by those who have! • But some students have! • good – it is definitely helpful • We try to meet the needs of the full range of students • Variety of different help and support available • Assignments have graduated components. • If you are repeating the course: • Do the whole of the assignments, without looking at previous solutions • The course will be similar, but there will be changes. © Peter Andreae

Planning Ahead: COMP 102: 12 • If you are doing BE or BSc (COMP)

Planning Ahead: COMP 102: 12 • If you are doing BE or BSc (COMP) or BSc (CGRA) or BSc (DATA) • then you should plan on taking COMP 103 in Tri 2. • If you are doing BE, or BSc (COMP or CGRA) • Don’t forget the maths courses that you need for 2 nd year! • If you are doing BSc (CGRA) • Don’t forget ANFX 101 • If you are doing BBmed. Sc or DATA • COMP 132 may be more relevant. © Peter Andreae

COMP 102: 13 Planning Ahead: Mathematics Engineering maths Mathematics maths • BE SWEN/CYBR: ENGR

COMP 102: 13 Planning Ahead: Mathematics Engineering maths Mathematics maths • BE SWEN/CYBR: ENGR 121, 123 or MATH 161, STAT 193/MATH 177 • BE ECEN: ENGR 121, 122 or MATH 151, 142 • BSc COMP: ENGR 121, 123 or MATH 161, STAT 193/MATH 177 • BSc CGRA: ENGR 121, 123, [122] or MATH 151 , 161, [142] Which should you take? © Peter Andreae

Planning Ahead: Mathematics COMP 102: 14 Which should you take? • Most students are

Planning Ahead: Mathematics COMP 102: 14 Which should you take? • Most students are better off with the Engineering maths option. • slower start • focused on application of mathematics • Students with good mathematics should consider the Mathematics maths option: • Opens more options in later years • Better background for postgraduate study, especially in computer graphics • If you have the following NCEA achievement standards: • 3. 6 (differentiation, AS 91578) and 3. 7 (integration, AS 91579) • one of 3. 5 (complex nos, AS 91577) or 3. 1 (conics, AS 91573) or 3. 3 (trigonometry, AS 91575) or 3. 13 (probability, AS 91585) or 3. 14 (probability distributions, AS 91586)). • At least 2 standards must be with grades of merit or excellence. • If you want to switch … © Peter Andreae

Course Organisation, Requirements, … COMP 102: 15 All the details are in the course

Course Organisation, Requirements, … COMP 102: 15 All the details are in the course outline: • on the course web page: http: //ecs. victoria. ac. nz/Courses/COMP 102_2018 T 1/ Course Outline and Additional Information. eg, the Mandatory Course Requirements…. © Peter Andreae

Course Information COMP 102: 16 Bookmark http: //ecs. victoria. ac. nz/Courses/COMP 102_2018 T 1

Course Information COMP 102: 16 Bookmark http: //ecs. victoria. ac. nz/Courses/COMP 102_2018 T 1 (also accessible via link on Black. Board) • Course Outline and Course Information, • Announcements and lecture Slides • Lab Assignment details (times, dates, handouts, files, submission, marks. . . ) • Forum, for questions and discussion • Info about doing work at home. • Java documentation • Other useful links Primary administrative communication channel. © Peter Andreae

What to do NOW! COMP 102: 17 • Sign up for the labs: https:

What to do NOW! COMP 102: 17 • Sign up for the labs: https: //student-sa. victoria. ac. nz / • choose ONE Thu/Fri Lab and ONE Mon/Tue Lab • Note: You need to be registered for the course (a) to sign up for a lab (b) to be able to use the school computers • Voting for a Class Rep • Put a message about yourself on the forum if you want to be class representative; the class will vote on Monday. © Peter Andreae

Lab assignments COMP 102: 19 • Ten assignments (roughly weekly), • hand out: Monday

Lab assignments COMP 102: 19 • Ten assignments (roughly weekly), • hand out: Monday • due: 9 am Monday (a week later) • Apply material from lectures and text book to practical programming problems. This is where your learning happens! • Done partly in scheduled lab sessions • First session: Mon/Tues ( exercises and getting started) • Second session: Thurs/Fri ( working on assignment with tutor support) • Further work required: expect at least 5 hours outside labs • any of the ECS labs, • on your home computer • This week’s lab is short, and doesn’t require additional work. © Peter Andreae

Getting Help. COMP 102: 20 Help Desk • Online help: • Forum for general

Getting Help. COMP 102: 20 Help Desk • Online help: • Forum for general questions; • email/web form for questions about your code. • Help Desk: Tutors available at various times at CO 242 a: see weekly timetable, starting wed in 3 rd week. Study groups • We will facilitate organising study groups and tutored help sessions • First year Engineering/Comp. Sci tutorials/help sessions • Excellent way of helping your learning • Awhina and Pasifika programmes: • Intend to facilitate support groups for Maori and Pasifika students • Women students support group. © Peter Andreae

Text Book and Handouts COMP 102: 21 Text Book • Java Foundations Lewis, De.

Text Book and Handouts COMP 102: 21 Text Book • Java Foundations Lewis, De. Pasquale, Chase • Same as for COMP 103. • [also OK: Java Software Solutions (6 th ed) Lewis and Loftus] • We consider it an important resource. • The lectures complement the text, not replace it. • Lectures will not cover all the details you need! • But nor will the textbook! Resources • Lecture slides & Assignments: On COMP 102 web page. © Peter Andreae

Tests and Exams COMP 102: 22 Terms Test 1: • 15% • Monday 1

Tests and Exams COMP 102: 22 Terms Test 1: • 15% • Monday 1 April 5 -6 pm Terms Test 2: • 15% • Tuesday 14 May 5 -6 pm Exam: • 50% • Date tba (between 9 June and 12 July) Note: If a test mark is less than your exam mark, we will raise the test mark to the exam mark. © Peter Andreae

COMP 102: 23 Assessment To pass the course, you must: • Satisfy the Mandatory

COMP 102: 23 Assessment To pass the course, you must: • Satisfy the Mandatory Requirement. • Get overall grade of C- or better. Mandatory Course Requirement: • Submit reasonable attempts ( at least D) for at least 8 of 10 assignments. Final Grade: • Assignments: 20% • Terms Test 1: Terms Test 2: Exam: 15% 50% (mark boosted to exam mark, if better) Penalties for late assignments: • 0 marks for late assignments, (Model solutions will be available) • But you have a total of 24 "late hours" that you can use to avoid penalties. © Peter Andreae

Withdrawal dates COMP 102: 24 • Early withdrawal with refund: up do Fri 14

Withdrawal dates COMP 102: 24 • Early withdrawal with refund: up do Fri 14 March • no consequences to early withdrawal • Standard withdrawal without refund: up to Friday 17 May • Withdrawal recorded • No grade recorded on transcript • BUT, withdrawal counts as a fail for determining "Satisfactory Academic Progress" • Late withdrawal with Dean's permission: after 17 May • Requires permission of Associate Dean • Normally given only when special circumstances arise after deadline. © Peter Andreae

Plagiarism (Cheating) COMP 102: 25 • You must not present anybody else’s work as

Plagiarism (Cheating) COMP 102: 25 • You must not present anybody else’s work as if it were your own work: • • Basic principle of academic honesty. applies to work by other students, friends, relatives, the web, books… If you received substantial help, then you must state who helped and how much. If you declare any work from someone else, then it isn’t plagiarism!!! • In COMP 102: • We encourage you to work in pairs on the core & completion parts of assignments BUT • You must put a comment at the top of your code saying that you worked with …. • If you use code from the assigned text book, or from the lectures, then you do not need to declare it; If you use any other code that wasn’t yours, then declare it! © Peter Andreae

Cheating in the assignments. COMP 102: 26 Assignments are primarily for learning, not assessing

Cheating in the assignments. COMP 102: 26 Assignments are primarily for learning, not assessing Cheating in the assignments is not worth it! • You won't learn, so you will probably fail. • If caught, you'll lose marks --- or worse. • Assignments have a fairly small contribution to your grade. © Peter Andreae

Lab Facilities COMP 102: 27 • All scheduled labs are in CO 219/238 •

Lab Facilities COMP 102: 27 • All scheduled labs are in CO 219/238 • Can also use other ECS labs (or other university student computing labs) • Can also use home computers. (Details on Web Site) • Lab Hours: 24/7 • Need ID card to access in evenings and weekends • The labs are for getting work done • Don’t prevent other people from working • If you want to play around, go somewhere else • We expect professional behaviour in the labs. Read the lab rules! © Peter Andreae

Where to go for Help COMP 102: 28 Depends on the kind of help

Where to go for Help COMP 102: 28 Depends on the kind of help needed • Course organiser / Lecturer, Senior Tutor, tutors (in labs or helpdesk only!) • Forum (via website) • On-line help system (via website) • Help desk (CO 242 a) • ECS School Office: CO 358 • Student Services: www. victoria. ac. nz/students/support • Science Faculty office: www. victoria. ac. nz/science/student-administration • www. victoria. ac. nz/maori-at-victoria/tautoko/maori-student-services • www. victoria. ac. nz/pasifika/our-community/pasifika-student-success • The Web © Peter Andreae

Getting Help: Inside COMP 102: 29 • Ask the tutors in your lab session

Getting Help: Inside COMP 102: 29 • Ask the tutors in your lab session • Ask a classmate, or someone else you know. • Put a message on the class forum • (can’t include any code from your answers, even if it is wrong) • Email to comp 102 -help@ecs. vuw. ac. nz • can include your code – only visible by staff and tutors • Go to the Tutorials on Tuesdays 4 -5, AM 106, Mondays/Wednesdays 5 -7, AM 106 • Go to the help desks. © Peter Andreae

NCEA vs University COMP 102: 31 • NCEA has lots of components with individual

NCEA vs University COMP 102: 31 • NCEA has lots of components with individual grades; not all needed. • being strategic on which components to do, and which to ignore • Uni has lots of components that are combined into a single grade; all count. • being strategic on how much time to put into each component. • NCEA (internal) may allow resubmission • Uni generally does NOT allow resubmission • NCEA focuses on getting Achieved; Excellence is very difficult. • if you have Achieved, may not be worth trying harder. • Uni focuses on grades; A’s are more achievable • Just passing is not enough • It’s worth doing more because it will increase your grade. © Peter Andreae

What is a Program COMP 102: 32 A program is a specification for the

What is a Program COMP 102: 32 A program is a specification for the behaviour of a computer: • What the computer should do when: • • • the program is started the user types something the user clicks the mouse a message arrives over the network some input from a camera/switch/sensor arrives. …… • Responses may be simple or very complex. • A program consists of • descriptions of responses to events/requests • written as instructions • in a language the computer can understand: • Lots of different programming languages; we will use Java © Peter Andreae

Learning to Program in Java COMP 102: 33 What’s involved? • Understand what the

Learning to Program in Java COMP 102: 33 What’s involved? • Understand what the computer can do and what the language can specify • Problem solving: • program design, • data structuring, • Programming language (Java): • syntax and semantics • style and common patterns • libraries of code written by other people • Testing and Debugging (fixing). • Common patterns in program design. • Important data structures and algorithms. © Peter Andreae

COMP 102: 34 A first Java Program • Task: Write a temperature conversion program

COMP 102: 34 A first Java Program • Task: Write a temperature conversion program • Step 1: Specification: what is it supposed to do? • Write a program that will let the user do two things: • print out the conversion formula • let user enter temperature in Fahrenheit, and print out in Celsius. • Step 2: Design: • For print action: • Print the formula on the window Two Actions • For calculate action: • Ask user for the Fahrenheit value to be converted • Calculate Celsius value out of given value: (F-32. 0)*5. 0/9. 0 • Print out the answer © Peter Andreae

Designing the Java program COMP 102: 35 Step 3: Editing • Need to write

Designing the Java program COMP 102: 35 Step 3: Editing • Need to write this design in the Java language. Need an object : a "temperature calculator" - all actions must be performed on some object Need a class to describe the object The class needs a name The class needs to specify the two actions its objects can do Define methods to do things. Give names to the methods specify what the methods will do © Peter Andreae

COMP 102: 36 Writing the Java code import ecs 100. *; /** Program for

COMP 102: 36 Writing the Java code import ecs 100. *; /** Program for converting between temperature scales */ public class Temperature. Calculator{ Comments Keywords /** Print conversion formula */ public void print. Formula ( ) { UI. println("Celsius = (Fahrenheit - 32) *5/9"); } Identifiers /** Ask for Fahrenheit and convert to Celsius */ public void do. Fahrenheit. To. Celsius(){ double fahrenheit = UI. ask. Double("Farenheit: "); double celsius = (fahrenheit - 32. 0) * 5. 0 / 9. 0; UI. println(fahrenheit + " F -> " + celsius + " C"); } Numbers Strings Types Operators Punctuation } © Peter Andreae

Elements of the program COMP 102: 37 Program Structure: • Import • list the

Elements of the program COMP 102: 37 Program Structure: • Import • list the "libraries" you will use (We always use ecs 100, and usually java. awt. Color and java. util. *) • Class • Top level component of program • Describes a class of objects • Specifies the set of actions this kind of object can perform • (Can also specify information the objects can hold) • Note name, and conventions for naming. • Methods • Main elements of a class • Each method describes an action that objects of this class can perform © Peter Andreae

Elements of the program COMP 102: 38 • Comments vs Code • Keywords /

Elements of the program COMP 102: 38 • Comments vs Code • Keywords / Identifiers / Strings / Types / numbers / operators and punctuation • Keywords : words with special meaning in the Java Language eg: public, class, if, while, … mostly to do with the structure of the program • Identifiers : other words, used to refer to things in the program. mostly made up by the programmer, some are predefined. • Strings : bits of text that the program will manipulate. always surrounded by " and " • Types : names for kinds of values. • numbers • operators and punctuation : + - * / = %. ; , ( ) { } [ ] ' " all have precise meanings and rules for use © Peter Andreae

COMP 102: 39 Actions in a program • Method calls object. method ( arguments

COMP 102: 39 Actions in a program • Method calls object. method ( arguments ) • telling an object to do one of its methods, passing the necessary information as arguments: UI. println("Celsius = (Fahrenheit - 32) *5/9"); UI. draw. Rect(100, 200, 50, 75); UI. add. Button(“Draw", this: : do. Draw); • What are the possible objects? what are the possible methods. • UI object has methods for • Printing, asking, drawing, buttons, …. • this object – the one we are defining – has the methods being defined in the class • Assignment statements place = value • putting a value in a place double celsius = (fahren – 32. 0) * 5. 0 / 9. 0; double fahren= UI. ask. Double(“Fahrenheit: "); © Peter Andreae

Blue. J COMP 102: 40 • Blue. J is an IDE for Java (Integrated

Blue. J COMP 102: 40 • Blue. J is an IDE for Java (Integrated Development Environment) • Class manager, for keeping track of the files in your program • Editor for entering and modifying the program • Built-in compiler interface to help compile and fix the syntax errors • Special interface to make it easy to construct objects and call methods on them. • Let’s do it… editing in Blue. J © Peter Andreae

Compiling and Running COMP 102: 41 Step 4: Compiling • If there are syntax

Compiling and Running COMP 102: 41 Step 4: Compiling • If there are syntax errors (invalid Java) then the compiler will complain and list all the errors ⇒ read the error message to work out what's wrong ⇒ fixing syntax errors until it compiles without complaint • Blue. J makes this process easier Let’s do it… © Peter Andreae

Compiling and Running COMP 102: 42 Step 4: Compiling • If there are syntax

Compiling and Running COMP 102: 42 Step 4: Compiling • If there are syntax errors (invalid Java) then the compiler will complain and list all the errors ⇒ read the error message to work out what's wrong ⇒ fixing syntax errors until it compiles without complaint • Blue. J makes this process easier Step 5: Running and Testing • Must run the program and test it on lots of different input. • Blue. J makes it easy to run individual methods. © Peter Andreae

Using Blue. J for Java Programs COMP 102: 43 Simple use of Blue. J

Using Blue. J for Java Programs COMP 102: 43 Simple use of Blue. J for simple programs: 1. Edit the class file(s) to define the methods 2. Compile the class 3. Create an object of the class • • right click on the rectangle representing the class select “new…. . ” ⇒ a red square representing the object 4. Call methods on the object • • right click on the square representing the object select the method. © Peter Andreae

Maze. Mouse COMP 102: 44 • Maze. Mouse – a Programming Puzzle © Peter

Maze. Mouse COMP 102: 44 • Maze. Mouse – a Programming Puzzle © Peter Andreae

Temperature Converter (again) COMP 102: 46 import ecs 100. *; /** Program for converting

Temperature Converter (again) COMP 102: 46 import ecs 100. *; /** Program for converting between temperature scales */ public class Temperature. Calculator{ /** Print conversion formula */ public void print. Formula ( ) { UI. println("Celsius = (Fahrenheit - 32) *5/9"); } /** Ask for Fahrenheit and convert to Celsius */ public void do. Fahrenheit. To. Celsius(){ double fahrenheit = UI. ask. Double("Farenheit: "); double celsius = (fahrenheit - 32. 0) * 5. 0 / 9. 0; UI. println(fahrenheit + " F -> " + celsius + " C"); } } © Peter Andreae

Writing your own programs COMP 102: 47 How? • Use other programs as models,

Writing your own programs COMP 102: 47 How? • Use other programs as models, and then modify • Very useful strategy • Lectures have examples that you can use as models for your assignment programs © Peter Andreae

A new program COMP 102: 48 • Calculator to • convert kilograms to pounds,

A new program COMP 102: 48 • Calculator to • convert kilograms to pounds, and to ounces • convert pounds and ounces to kilograms import ecs 100. *; /** Program to convert weights */ public class Temperature. Calculator{ public void do. Fahrenheit. To. Celsius(){ double fahrenheit = UI. ask. Double("Farenheit: "); double celsius = (fahrenheit – 32. 0) * 5. 0 / 9. 0; UI. println(fahrenheit + " F -> " + celsius + " C"); } © Peter Andreae

Writing your own programs COMP 102: 49 How? • Use other programs as models,

Writing your own programs COMP 102: 49 How? • Use other programs as models, and then modify • Very useful strategy BUT • It can be hard to work out how to modify Need to understand the language ⇒ vocabulary ⇒ syntax rules ⇒ meaning (“semantics”) © Peter Andreae

COMP 102: 50 Syntax rules: Program structure • First version import ecs 100. *;

COMP 102: 50 Syntax rules: Program structure • First version import ecs 100. *; import java. awt. Color; 〈import statements〉 public class 〈classname〉 { 〈method description〉 } Comments can be added anywhere © Peter Andreae

COMP 102: 51 Comments Top of class, Before each method Three kinds of comments:

COMP 102: 51 Comments Top of class, Before each method Three kinds of comments: • Documentation comments /** eg 〈text of comment〉 */ /** Program for converting between temperature scales */ • end-of-line comments // eg at end of any line 〈text of comment〉 double celsius = (fahren – 32. 0) * 5. 0 / 9. 0; // compute answer multi-line, or middle of line, or … • anywhere comments /* eg 〈text of comment〉 */ /* double fahren = celsius * 9 / 5 + 32; UI. println(celsius + “C is " + fahren + " F"); */ © Peter Andreae

COMP 102: 52 Method Definitions /** Print out the conversion formulas */ public void

COMP 102: 52 Method Definitions /** Print out the conversion formulas */ public void print. Formula ( ) { UI. println("Celsius = (Fahrenheit - 32) *5/9"); instructions to perform this action } 〈Doc Comment〉 public { 〈Header〉 void 〈name〉 ( } 〈Body〉 〈parameters〉 ) Specifying the information the action needs. May be empty © Peter Andreae

“Statements” (instructions) COMP 102: 53 (programmer jargon: single instructions are called “statements” for silly

“Statements” (instructions) COMP 102: 53 (programmer jargon: single instructions are called “statements” for silly historical reasons!) Two important kinds of statements: • method call statement: • tell some object to perform one of its methods. eg: tell the UI object to ask the user for a number eg: tell this object to print the celsius value of a temperature eg: tell the UI object to print out a string eg: tell the UI object to add a button • assignment statement • compute some value and put it in a place in memory. © Peter Andreae

COMP 102: 54 Method Calls /** Print out the conversion formulas */ public void

COMP 102: 54 Method Calls /** Print out the conversion formulas */ public void print. Formula(){ UI. println( "Celsius = (Fahrenheit - 32) *5/9" ); } • Method call Statement: who . what 〈object〉 . UI . 〈methodname〉 println ( data to use ( 〈arguments〉 ( “Celsius = (Fahren…” ) ; • Meaning of Statement: • Tell the object to perform the method using the argument values provided © Peter Andreae

COMP 102: 55 Objects and their methods in Java • What objects are there?

COMP 102: 55 Objects and their methods in Java • What objects are there? Predefined eg: • UI a "User Interface" window with several panes initialize() quit() add. Button(…) println(…. ) draw. Rect(…) ask. Double(…) ask. String(…) clear. Graphics(), • Math methods for mathematical calculations random( ), sin(…) • System representing the computer system current. Time. Millis( ) Others • this The object(s) defined by this class in your program • New objects that your program creates Some method calls return a value © Peter Andreae

COMP 102: 56 Values / Data There are lots of different kinds ("Types") of

COMP 102: 56 Values / Data There are lots of different kinds ("Types") of values: • Numbers • Integers • real numbers • … ( int or long) 42 ( double or float ) 42. 0 -194573203 16. 43 6. 626 e-34 • Characters ( char ) 'X' '4' • Text ( String ) " F -> " • Colours ( Color ) Color. red • Methods Color. green this: : do. Fahrenheit. To. Celsius • Other Objects • … © Peter Andreae

Assignment 1 COMP 102: 58 • Calculator programs • Programs to draw flags and

Assignment 1 COMP 102: 58 • Calculator programs • Programs to draw flags and other shapes • core/completion/challenge • core is based fairly directly on the lectures • completion requires more problem solving • challenge may require finding additional stuff out for yourself. © Peter Andreae

COMP 102: 59 Variables /** Convert from fahrenheit to Celsius */ public void do.

COMP 102: 59 Variables /** Convert from fahrenheit to Celsius */ public void do. Fahrenheit. To. Celsius(){ double fahrenheit = UI. ask. Double("Fahrenheit: " ); double celsius = (fahrenheit – 32. 0) * 5. 0 / 9. 0; UI. println(fahrenheit + “F is " + celsius + “ C"); } Use a variable whenever you need the computer to remember something temporarily. • A variable is a place in memory that can hold a value. • Must specify the type of value that can be put in the variable ⇒ “Declare” the variable first time it is mentioned. 〈type〉 Asking for a place 〈variable〉 • Must put a value into a variable before you can use it ⇒ “assign” to the variable • Can use the value by specifying the variable’s name • Can change the value in a variable (unlike mathematical variable) © Peter Andreae

COMP 102: 60 Assignment Statements /** Convert from fahrenheit to Celsius */ public void

COMP 102: 60 Assignment Statements /** Convert from fahrenheit to Celsius */ public void do. Fahrenheit. To. Celsius(){ double fahrenheit = UI. ask. Double("Fahrenheit: " ); double celsius = (fahrenheit – 32. 0) * 5. 0 / 9. 0; UI. println(fahrenheit + “F is " + celsius + “ C"); } Putting a value into a variable • Assignment Statement: where = 〈variable〉 = what ; 〈expression〉 ; name-of-place = specification-of-value ; formula = " Celsius = (Fahrenheit - 32) *5/9" Meaning: Compute the value and put it in the place © Peter Andreae

Expressions /** Convert from fahrenheit to Celsius */ public void do. Fahrenheit. To. Celsius(){

Expressions /** Convert from fahrenheit to Celsius */ public void do. Fahrenheit. To. Celsius(){ COMP 102: 61 combining declaration and assignment into a single line double fahrenheit = UI. ask. Double("Fahrenheit: " ); double celsius = (fahrenheit – 32. 0) * 5. 0 / 9. 0; UI. println(fahrenheit + “F is " + celsius + “ C"); } + for Strings: "concatenates" the Strings • Expressions describe how to compute a value. • Expressions are constructed from • • • values variables operators (+, -, *, /, etc) method calls that return a value sub-expressions, using (… ) … © Peter Andreae

Method Calls and variables: a metaphor COMP 102: 62 Method Definition: Like a pad

Method Calls and variables: a metaphor COMP 102: 62 Method Definition: Like a pad of worksheets public voiddo. Fahrenheit. To. Celsius(){ doublefahrenheit= =UI. ask. Double("Fahrenheit: "); doublecelsius= =(fahrenheit– – 32) 32. 0) double * 5*/5. 0 9; / 9. 0; Fahrenheit: 86 86. 0 F is 30. 0 C UI. println(fahrenheit + “isis""++celsius++ ““C"); UI. println(fahrenheit + “F } 86 0 Calling a Method: 30 0 temp. Calc 1. fahrenheit. To. Celsius(); ⇒ get a “copy” of the method worksheet ⇒ perform each action in the body. ⇒ throw the worksheet away (losing all the information on it) © Peter Andreae

Summary of Java program structure COMP 102: 63 • A Class specifies a type

Summary of Java program structure COMP 102: 63 • A Class specifies a type of object • Temperature. Calculator. class describes Temperature. Calculator objects • A Class contains a collection of methods • Each method is an action the objects can perform. • Temperature. Calculator objects can do celsius. To. Fahrenheit, fahrenheit. To. Celsius, print. Formula • If you have an object, you can call its methods on it. • A method definition contains statements • Each statement specifies one step of performing the action • Method call statements • Declaration and Assignment statements © Peter Andreae

COMP 102: 65 Programs with graphics output • Write a program to draw a

COMP 102: 65 Programs with graphics output • Write a program to draw a lollipop: Design (0, 0) • What shapes can we draw? • UI has methods to draw rectangles, ovals, lines, arcs, … ⇒ Draw one thick black line one red oval, Shapes are drawn on top of previous shapes • How do we draw them? Need to set the color first (initially black) then call the draw/fill methods: • must specify the positions and size • rectangles/ovals: left, top, width, height • lines: x and y of each end. y x Coordinates measured from left and top © Peter Andreae

COMP 102: 66 Some UI methods Text: UI. clear. Text() UI. print(anything ) UI.

COMP 102: 66 Some UI methods Text: UI. clear. Text() UI. print(anything ) UI. println(anything ) UI. ask. String(prompt-string ) UI. ask. Token(prompt-string ) UI. ask. Double(prompt-string ) UI. ask. Int(prompt-string ) UI. printf( format-string, values…) UI. ask. Boolean(prompt-string ) Graphics: Eg: Color. red UI. clear. Graphics() UI. set. Color(color ) UI. set. Line. Width(width ) UI. draw. Rect(left, top, wd, ht ) UI. fill. Rect(left, top, wd, ht ) UI. draw. Oval(left, top, wd, ht ) UI. fill. Oval(left, top, wd, ht ) UI. draw. Line(x 1, y 1, x 2, y 2 ) UI. draw. Image(file, left, top ) …… © Peter Andreae

Read the Documentation! COMP 102: 67 • Full documentation for all the standard Java

Read the Documentation! COMP 102: 67 • Full documentation for all the standard Java library code (the "API" : Application Programming Interface) • Version of Java API documentation on course web site: • "Java Documentation" in side bar • http: //ecs. victoria. ac. nz/foswiki/pub/Main/Java. Resources/java. API-102. html • Tailored for Comp 102 • Includes documentation of the ecs 100 library: (UI, Trace, etc, ) • puts most useful classes at the top of the list. • Use the documentation while you are programming! • Control-space in Bluej brings up the options plus documentation. © Peter Andreae

COMP 102: 68 Writing the program • Need import statements • Need a class

COMP 102: 68 Writing the program • Need import statements • Need a class (with a descriptive comment) • Need a method (with a descriptive comment) import ecs 100. *; import java. awt. Color; /** Draws little shapes on the graphics pane */ public class Drawer { } /** Draw an red lollipop with a stick */ public void draw. Lollipop() { // actions } Write the method body as comments first © Peter Andreae

Writing the program: using comments import ecs 100. *; import java. awt. Color ;

Writing the program: using comments import ecs 100. *; import java. awt. Color ; COMP 102: 69 Do it in Blue. J! /** Draws little pictures on the graphics pane */ public class Drawer { /** Draw an red lollipop on a stick */ public void draw. Lollipop() { // set line width to 10 // draw line (300, 200) to (300, 400) // set line width to 1 // set color to red // fill oval @(260, 160) 80 x 80 } Now express each comment in Java (look up documentation as necessary) } © Peter Andreae

Writing the program COMP 102: 70 import ecs 100. *; import java. awt. Color

Writing the program COMP 102: 70 import ecs 100. *; import java. awt. Color ; /** Draws little pictures on the graphics pane */ public class Drawer { /** Draw a lollipop */ public void draw. Lollipop() { UI. set. Line. Width(10); // set line width to 10 UI. draw. Line(300, 200, 300, 400); // draw line UI. set. Line. Width(1); // set line width back to 1 UI. set. Color(Color. red); // set color to red UI. fill. Oval(260, 160, 80); // draw blob } } Now compile and run the program © Peter Andreae

Class Reps COMP 102: 71 • Only two candidates. • We have two streams

Class Reps COMP 102: 71 • Only two candidates. • We have two streams => two class reps is reasonable • Ethan Fransen • Joel Bason-de-Brouwer • We will put their contact details on the web site. • Contact them if you have concerns about the course that you would like them to bring to me. (They will do it anonymously) • Ethan and Joel: please register on the VUWSA page (linked on forum) © Peter Andreae

A model/metaphor for the computer COMP 102: 72 • If you are giving instructions

A model/metaphor for the computer COMP 102: 72 • If you are giving instructions to someone/something, it helps to understand how they think and what they can do! • Your program is run by the "Java Virtual Machine" • The JVM is like a clerk • with memory loss – only remembers what they write down • with a clipboard for the worksheets with the instructions they are currently working on • looking at the back of the UI window which they can write/paint on, but the writing/painting only appears on the outside – they can't see what they did before • can see a stream of characters that the user types on the keyboard © Peter Andreae

Lollipop Drawing program COMP 102: 73 import ecs 100. *; import java. awt. Color

Lollipop Drawing program COMP 102: 73 import ecs 100. *; import java. awt. Color ; /** Draws little pictures on the graphics pane */ public class Drawer { /** Draw a lollipop */ public void draw. Lollipop() { UI. set. Color(Color. black); UI. set. Line. Width(10); UI. draw. Line(200, 300, 200, 400); UI. set. Line. Width(1); UI. set. Color(Color. red); UI. fill. Oval(260, 160, 80); } // set color to black // set line width to 10 // draw line // set line width back to 1 // set color to red // draw blob } © Peter Andreae

Improving the design COMP 102: 74 • This program is very inflexible: • What

Improving the design COMP 102: 74 • This program is very inflexible: • What if • • • We want the lollipop to be in a different position? We want the lollipop to be bigger or smaller? We want the stick to be longer? …. We want to draw two of them? • Current design is filled with literal values ⇒ difficult to understand ⇒ difficult to change (have to find all the places and redo all the arithmetic © Peter Andreae

COMP 102: 75 Move or resize the Lollipop. import ecs 100. *; import java.

COMP 102: 75 Move or resize the Lollipop. import ecs 100. *; import java. awt. Color ; /** Draws little pictures on the graphics pane */ public class Drawer { /** Draw a lollipop */ public void do. Draw. Lollipop() { UI. set. Color(Color. black); UI. set. Line. Width(10); UI. draw. Line(300, 200, 300, 400); UI. set. Line. Width(1); UI. set. Color(Color. red); UI. fill. Oval(260, 160, 80); } } Move it left Move it down // set color to black // set line width to 10 // draw line // set line width back to 1 // set color to red // draw blob Change blob size © Peter Andreae

Improving the design COMP 102: 76 • Better design: Use named constants and variables

Improving the design COMP 102: 76 • Better design: Use named constants and variables ⇒ easier to write and easier to change ⇒ get the computer to do the arithmetic • Use named constants for values that won’t change while the program is running. © Peter Andreae

COMP 102: 77 Values to specify lollipop & stick y x size stick ©

COMP 102: 77 Values to specify lollipop & stick y x size stick © Peter Andreae

COMP 102: 78 Improving the program: constants import ecs 100. *; import java. awt.

COMP 102: 78 Improving the program: constants import ecs 100. *; import java. awt. Color; Easy to change: /** Draw a lollipop with a stick */ one place! public class Drawer { public static final double X = 300. 0; // horizontal center of lollipop public static final double Y = 180. 0; // vertical center of lollipop public static final double SIZE = 80. 0; // diameter of lollipop public static final double STICK = 200. 0; // length of lollipop stick } /** Draw a lollipop */ public void do. Draw. Lollipop() { UI. set. Line. Width(SIZE/8. 0); UI. draw. Line(X, Y, X, Y+STICK); UI. set. Line. Width(1); UI. set. Color(Color. red); UI. fill. Oval(X-SIZE/2. 0, Y-SIZE/2. 0, SIZE); } y x size stick © Peter Andreae

COMP 102: 79 Syntax rules: Program structure • 2 nd version 〈import statements〉 public

COMP 102: 79 Syntax rules: Program structure • 2 nd version 〈import statements〉 public class 〈classname〉 { Defining a constant 〈constant definition〉 public static final 〈method description〉 〈type〉 } 〈name〉 = 〈value〉 ; © Peter Andreae

Improving the program: more names COMP 102: 80 public static final double X =

Improving the program: more names COMP 102: 80 public static final double X = 300. 0; // horizontal center of lollipop public static final double Y = 180. 0; // vertical center of lollipop public static final double SIZE = 80. 0; // diameter of lollipop public static final double STICK = 200. 0; // length of lollipop stick Still have a problem: /** Draw a lollipop */ What do these expressions mean? public void do. Draw. Lollipop() { UI. set. Line. Width(10); UI. draw. Line(X, Y, X, Y+STICK); UI. set. Line. Width(1); UI. set. Color(Color. red); UI. fill. Oval(X-SIZE/2. 0, Y-SIZE/2. 0, SIZE); } © Peter Andreae

COMP 102: 81 Values to specify lollipop & stick top y left x size

COMP 102: 81 Values to specify lollipop & stick top y left x size stick bot Useful to have more named values! © Peter Andreae

Improving the program: variables COMP 102: 82 public static final double X = 300.

Improving the program: variables COMP 102: 82 public static final double X = 300. 0; // horizontal center of lollipop public static final double Y = 180. 0; // vertical center of lollipop public static final double SIZE = 80. 0; // diameter of lollipop public static final double STICK = 200. 0; // length of lollipop stick /** Draw a lollipop */ public void do. Draw. Lollipop() { double left = X – SIZE/2. 0; double top = Y – SIZE/2. 0; double bot = Y + STICK; UI. set. Line. Width(10); UI. draw. Line(X, Y, X, bot); UI. set. Line. Width(1); UI. set. Color(Color. red); UI. fill. Oval(left, top, SIZE); } // left of lollipop // top of lollipop // bottom of stick © Peter Andreae

Principle of good design COMP 102: 83 • Use well named constants or variables

Principle of good design COMP 102: 83 • Use well named constants or variables wherever possible, rather than literal values ⇒ easier to understand ⇒ easier to get right ⇒ much easier to modify • Choosing the right constants or variables is an art!! • why did I choose “x" instead of “left" ? • why did I choose “y" instead of stick bottom? • We have effectively parameterised the drawing • Four values (X, Y, SIZE, STICK) control the whole thing. © Peter Andreae

Even better design: parameters COMP 102: 84 • Every time we want a lollipop

Even better design: parameters COMP 102: 84 • Every time we want a lollipop of a different size or in a different position, we have to modify the code. • How come we don't have to do that with draw. Rect? • draw. Rect has four parameters: In the library files Parameters Definition of draw. Rect: public void draw. Rect(double left, double top, double wd, double ht) {……} In our program Calling draw. Rect: UI. draw. Rect(200, 150, 80), UI. draw. Rect(400, 120, 85, 0), Arguments ⇒ draw. Rect can make many different rectangles. Why can't we do that with lollipop? © Peter Andreae

COMP 102: 85 Improving the program: using parameters /** Draw a lollipop at (300,

COMP 102: 85 Improving the program: using parameters /** Draw a lollipop at (300, 180), asking the user for its size */ public void do. Draw. Lollipop() { double size = UI. ask. Double("Diameter: "); double stick. Height = UI. ask. Double("Stick height"); this. draw. Lollipop(300, 180, size, stick. Height); } y x size stick. Height public void draw. Lollipop(double x, double y, double size, double stick) { double left = x – size/2. 0; double top = y – size/2. 0; double bot = y + stick; UI. set. Line. Width(10); UI. draw. Line(x, y, x, bot); UI. set. Line. Width(1); UI. set. Color(Color. red); UI. fill. Oval(left, top, size); } // left of lollipop // top of lollipop // bottom of stick Parameters Special variables which are given values each time the method is called. Body of method can use the values in the parameters © Peter Andreae

COMP 102: 86 Syntax: Method Definitions (v 2) /** Draw a lollipop on a

COMP 102: 86 Syntax: Method Definitions (v 2) /** Draw a lollipop on a stick */ public void draw. Lollipop(double x, double y, double size, double stick ){ double left = x – size/ 2. 0; : 〈Comment〉 public void { 〈Header〉 〈name〉 How do you call a method with parameters from Blue. J? ( 〈Body〉 〈parameters〉 〈type〉 } ) 〈name〉 , © Peter Andreae

Method Calls with parameters COMP 102: 87 Method Definition: Like a pad of worksheets

Method Calls with parameters COMP 102: 87 Method Definition: Like a pad of worksheets public void draw. Lollipop( double x, x, double y, y, double size, double stick){ 300 0 100 0 75 0 95 0 double left == xx––size//2. 0; double top == yy––size//2. 0; : : }} UI. fill. Oval(left, top, size, size); Calling a Method: this. draw. Lollipop(300, 100, 75, 95); ⇒ get a “copy” of the method worksheet ⇒ copy the arguments to the parameter places ⇒ perform each action in the body ⇒ throw the worksheet away (losing all the information on it) © Peter Andreae

COMP 102: 88 Calling draw. Lollipop public class Drawer { public void do. Draw.

COMP 102: 88 Calling draw. Lollipop public class Drawer { public void do. Draw. Lollipops() { double diam = UI. ask. Double("diameter: "); this. draw. Lollipop(300, 180, diam, 200); this. draw. Lollipop(50, 60, diam/2. 0, 90); this. draw. Lollipop(400, 100, diam, 70); } /** Draw a lollipop */ public void draw. Lollipop(double x, double y, double size, double stick) { double left = x – size/2. 0; double top = y – size/2. 0; double bot = y + stick; UI. set. Line. Width(10); UI. draw. Line(x, y, x, bot); UI. set. Line. Width(1); UI. set. Color(Color. red); UI. fill. Oval(left, top, size); // left of lollipop // top of lollipop // bottom of stick © Peter Andreae

Principle of good design COMP 102: 89 • Parameterising a method makes it more

Principle of good design COMP 102: 89 • Parameterising a method makes it more flexible and general • Allows us to call the same method with different arguments to do the same thing in different ways • Allows us to reuse the same bit of code © Peter Andreae

COMP 102: 90 Arithmetic in Java • normal arithmetic operators: + – * and

COMP 102: 90 Arithmetic in Java • normal arithmetic operators: + – * and / • on doubles, operators work as expected length / 2. 5 => length: . 10 0 • + on Strings, (or a String and another value): • turns other value to a String, • Concatenates them together "Size is " + length + "cm" => • on integers, • does "primary school" arithmetic • / (division) gives a whole number num. Doors: 3 num. Walls: 8 • % gives the remainder 15 / 4 => 15 % 4 => num. Doors / num. Walls => 15 / 30 => 1. 0 * num. Doors / num. Walls => © Peter Andreae

Where have we been? COMP 102: 93 • Statements, (to specify instructions): • calling

Where have we been? COMP 102: 93 • Statements, (to specify instructions): • calling methods on objects, specifying arguments • text output, text input, graphical output. • declaring variables, • assigning values to variables (including new objects) • Expressions and values • • literal values constants variables combining values with operations (+, -, *, etc) • Defining methods • giving methods parameters • passing values to methods when you call the method • using parameter values in the method © Peter Andreae

Programs that make decisions COMP 102: 94 • Programs that perform the same action

Programs that make decisions COMP 102: 94 • Programs that perform the same action every time are boring! • You can vary the action in a program by getting input from the user: String name = UI. ask. String("name: "); : UI. printf("Hello %s, how are you? ", name); © Peter Andreae

Programs that make decisions COMP 102: 95 • But this just changes the values,

Programs that make decisions COMP 102: 95 • But this just changes the values, not the action itself. • To vary the action inside a method: • Need a conditional, or choice, statement: IF some condition is true THEN do this action ELSE do that action We do this in English instructions all the time: IF you solved the mouse maze THEN raise your hand IF your name starts with “A” or your name starts with “J” THEN draw a small circle in the top left corner of your notes ELSE draw a small square in the bottom right corner of your notes. © Peter Andreae

Decisions in Java COMP 102: 96 Java has an if … else … statement:

Decisions in Java COMP 102: 96 Java has an if … else … statement: • Can do an action only in some circumstances: if ( count. Times > 10 ) { UI. clear. Graphics(); this. draw. Board(10, 100); } • Can choose between different actions: if ( user. Choice. equals(“Yes" ) ){ UI. draw. Image("Nod. png", left, top); } else { UI. draw. Image(“Shake. png“, left, top); } © Peter Andreae

Java: if and if … else COMP 102: 97 LDC 4. 2 • Two

Java: if and if … else COMP 102: 97 LDC 4. 2 • Two forms of the if statement: if (〈condition 〉) { 〈actions to perform if condition is true 〉 } ⇒ just skip the actions when the condition is not true ! and if (〈condition 〉 ) { 〈actions to perform if condition is true 〉 } else { 〈actions to perform if condition is false 〉 } Note: the { … } represent a "Block" – a sequence of actions that are wrapped up together into a single statement. © Peter Andreae

if … vs COMP 102: 98 if … else … if boolean valued expression

if … vs COMP 102: 98 if … else … if boolean valued expression ( ) { statements } else { statements } © Peter Andreae

COMP 102: 99 Method with a condition /** Ask for amount and currency; print

COMP 102: 99 Method with a condition /** Ask for amount and currency; print note if –ve, print value. */ public void convert. Money( ) { ; double amount = UI. ask. Double("Enter amount $NZ"); if ( amount < 0 ) { UI. println("Note: you have entered a debt!"); } String currency = UI. ask. String ("Enter currency (US or Aus)"); Like println, but can control the format: %. 2 f floating point, 2 dp %d integer %s string n new line if ( currency. equals("US") ) { UI. printf("$NZ%. 2 f = $US%. 2 fn", amount, (amount * 0. 668)); } What is printf? else { UI. printf("$NZ%. 2 f = $AUS%. 2 fn", amount, (amount * 0. 893)); } } © Peter Andreae

Multiway choice: if … else if … COMP 102: 100 • Can put another

Multiway choice: if … else if … COMP 102: 100 • Can put another if statement in the else part: if (〈condition 1 〉 ) { 〈actions to perform if condition 1 is true〉 : } else if (〈condition 2 〉 ) { 〈actions to perform if condition 2 is true (but not condition 1) 〉 : } else if (〈condition 3 〉 ) { 〈actions to perform if condition 3 is true (but not conditions 1, 2)〉 : } else { 〈actions to perform if other conditions are false〉 : } © Peter Andreae

Example with multiway choice COMP 102: 101 public void convert. Money( ) { double

Example with multiway choice COMP 102: 101 public void convert. Money( ) { double amount = UI. ask. Double("Enter amount"); if (amount < 0 ) { UI. println("Note: you have entered a debt!"); } String currency = UI. ask. String("Enter currency (US or Aus)"); if (currency. equals("US") ) { UI. printf("$NZ%. 2 f = $US%. 2 f%n", amount * 0. 668); } else if ( currency. equals("Aus") ) { UI. printf("$NZ%. 2 f = $AUS%. 2 fn", amount * 0. 893); } else { UI. printf("I cannot convert to %s currency%n", currency); } } © Peter Andreae

Example 2 with multi way choice COMP 102: 102 public void print. Pay( int

Example 2 with multi way choice COMP 102: 102 public void print. Pay( int day, int hours ) { double rate = 13. 45; } double pay = rate * hours; if ( day > 7 ) { UI. println(" Day must be between 1 and 7 "); } else if ( day < 6 ) { UI. printf("Pay = $ %. 2 f %n", pay); } else if ( day == 6 ) { pay = pay * 1. 5; UI. printf("Pay = $ %. 2 f ( time-and-a-half) %n", pay); } else { pay = pay * 2; UI. printf("Pay = $ %. 2 f ( double-time) %n", pay); } © Peter Andreae

Boolean expressions LDC 4. 1 What can go in the condition of an if

Boolean expressions LDC 4. 1 What can go in the condition of an if statement? • A Boolean value – a value that is either true or false. • Boolean expressions: • constant values: true, false • numeric comparisons: (x > 0) (day <= 7), (x == y), (day != 7) • boolean method calls: month. equals("July") word. contains("th") COMP 102: 103 more methods on String equals. Ignore. Case("John”) starts. With(“Ab”) ends. With(“ies”) • boolean variables: outline. Only [ if declared boolean outline. Only; ] • logical operators: !, &&, || (not, and, or) ( x > 0 && x < 7 && outline. Only ) ( month. starts. With("Ju") || month. equals("May") ) ( ! file. Modified || ! (cmd. equals("exit")) ) © Peter Andreae

Writing Boolean expressions COMP 102: 104 Mostly, boolean expressions are straightforward, There are just

Writing Boolean expressions COMP 102: 104 Mostly, boolean expressions are straightforward, There are just a few traps: • == is the "equals" operator for simple values, = is assignment (age == 15) vs (age = 15 ); • But only use == for numbers (or characters, or references) • Use the equals method for Strings, not == (occasionally == will give the right answer by chance!) cur. equals("US") vs cur == "US" • String equality is case sensitive: “NZ". equals(“nz") “NZ". equals. Ignore. Case(“nz") → false → true © Peter Andreae

Boolean Variables COMP 102: 105 • A boolean value is a value! ⇒ it

Boolean Variables COMP 102: 105 • A boolean value is a value! ⇒ it can be stored in a variable. • Useful if the program needs to remember some option. • Must declare the variable, and assign to it, before using it boolean print. Steps = UI. ask. Boolean("Print all steps? "); : if ( print. Steps ) UI. println("Processed input"); : if ( print. Steps ) UI. println("Computed Statistics"); : © Peter Andreae

Compound Boolean expressions: operators COMP 102: 106 Using logical operators: Not: ! eg (

Compound Boolean expressions: operators COMP 102: 106 Using logical operators: Not: ! eg ( ! currency. equals. Ignore. Case(“US") ) And: && eg ( x > 0 && x < 7 && outline. Only ) Evaluates each conjunct in turn. If any conjunct false, then value of whole expression is false If all conjuncts true, then value of whole expression is true Or: || eg ( month. starts. With("Ju") || month. equals("May") ) Evaluates each disjunct in turn. If any disjunct true, then value of whole expression is true If all disjuncts false, then value of whole expression is false Can combine into complicated expressions: ( ! file. Modified || ( cmd. equals("exit") && last. Save. Time > 5000) ) safest to use lots of (…) © Peter Andreae

Traps with Boolean expressions COMP 102: 107 • When combining with && and ||,

Traps with Boolean expressions COMP 102: 107 • When combining with && and ||, which binds tighter? if ( x > 5 && y <= z || day == 0 ) { …. • Use ( and ) whenever you are not sure! if ( ( x > 5 && y <= z ) || day == 0 ) { … if ( x > 5 && ( y <= z || day == 0 ) ) { … • The not operator ! goes in front of expressions: • if ( !(x > 5 && y <= z ) { … NOT if ( (x !> 5 && y !<= z ) • if ( ! cur. equals("US") ) { … NOT if ( cur. !equals("US") ) { … • exception: OR if ( ! (count == 0) ) { … if ( count != 0 ) { … © Peter Andreae

Object oriented programming COMP 102: 110 • Key idea of OO programming • program

Object oriented programming COMP 102: 110 • Key idea of OO programming • program structured into classes of objects. • each class specifies a kind of object – eg, the actions it can perform. • Calling methods in OO languages like java • tell an object to perform a method, passing arguments • Making objects • Some objects are predefined. • Create objects with bluej: • Right-click on class, and select new …… • This is how we run programs with Blue. J. • not standard, and not a general solution © Peter Andreae

Objects COMP 102: 111 Question: How can a program make new objects? More Questions:

Objects COMP 102: 111 Question: How can a program make new objects? More Questions: What is an object anyway? Why do we need them? • An object is typically a collection of data with a set of actions it can perform. • The objects we have made so far are a bit strange – no data; just actions. (Temperature. Converter, Drawer) © Peter Andreae

Examples of objects COMP 102: 112 Butterfly program • Each butterfly is represented by

Examples of objects COMP 102: 112 Butterfly program • Each butterfly is represented by an object which stores the state of the butterfly (position, wing state, direction) • Butterflies have methods • move(double dist) and • land() • Cartoon. Figure program • Each cartoon figure is represented by an object which stores the state of the cartoon figure (image, position, direction facing, smile/frown). • Cartoon. Figure objects have methods • walk(double dist) • smile() frown() • look. Left() look. Right() • speak(String words) think(String words) © Peter Andreae

COMP 102: 113 Using objects • If the variable bf 1 and bf 2

COMP 102: 113 Using objects • If the variable bf 1 and bf 2 contained Butterfly objects, you could do: public void show. Butterflies(){ Butterfly bf 1 = ? ? ? Butterfly bf 2 = ? ? ? bf 1. move(10); bf 2. move(20); bf 1. land(); bf 2. move(20); bf 1. move(5); } Nothing new here: Just standard method calls! Problem: How do you get a Butterfly object into the variables? © Peter Andreae

COMP 102: 114 Creating Objects • Need to construct new objects: • New kind

COMP 102: 114 Creating Objects • Need to construct new objects: • New kind of expression: new Calling the constructor Butterfly bf 1 = new Butterfly( 100, … 300 … ) Creates a new object, which is put into bf 1 • Constructor calls are like method calls that return a value. • have ( ) • may need to pass arguments • returns a value – the new object that was constructed. • Constructor calls are NOT method calls • there is no object to call a method on. • must have the keyword new • name must be the name of the class © Peter Andreae

COMP 102: 115 Creating Objects: new Butterfly b 1 = new Butterfly(100, 300); UI.

COMP 102: 115 Creating Objects: new Butterfly b 1 = new Butterfly(100, 300); UI. set. Color( new Color(255, 190, 0) ); new 〈Class name〉 ( 〈arguments〉 ) • Calling a constructor: • new • Butterfly • (…) ( a keyword) ( the type of object to construct ) (arguments: specifying information needed to construct the new object) • This is an expression: it returns the new object • can put in a variable • can use in an enclosing expression or method call © Peter Andreae

COMP 102: 116 Reading Documentation • Documentation of a class: Bluej lets you see

COMP 102: 116 Reading Documentation • Documentation of a class: Bluej lets you see the documentation of your classes • Specifies the methods: • name • type of the return value (or void if no value returned) • number and types of the parameters. void move (double dist) moves the butterfly by dist, in its current direction. • Specifies the constructors: • number and types of the parameters (name is always the name of the class, return type is always the class) Butterfly(double x, double y) requires the initial position of the butterfly © Peter Andreae

Example: Butterfly Grove program public class Butterfly. Grove{ /** A grove of Butterflies which

Example: Butterfly Grove program public class Butterfly. Grove{ /** A grove of Butterflies which fly around and land */ public void one. Butterfly(){ Butterfly b 1 = new Butterfly(50, 20); b 1. move(5); b 1. move(10); b 1. move(11); b 1. move(12); b 1. move(13); b 1. move(14); b 1. move(15); b 1. move(16); b 1. move(10); b 1. land(); } COMP 102: 117 public void two. Butterflies(){ Butterfly b 1 = new Butterfly(100, 20); b 1. move(5); b 1. move(10); b 1. move(15); double x = 400*Math. random(); Butterfly b 2 = new Butterfly(x, 40); b 2. move(10); b 1. move(15); b 2. move(10); b 1. move(12); b 2. move(10); b 1. move(11); b 1. move(7); b 1. land(); b 2. move(20); b 2. move(25); b 2. land(); } © Peter Andreae

Objects are values too: COMP 102: 118 • Objects can be passed to methods,

Objects are values too: COMP 102: 118 • Objects can be passed to methods, just like other values. public void Butterflies(){ Butterfly b 1 = new Butterfly(100, 20); Butterfly b 2 = new Butterfly(x, 40); this. up. And. Down(b 1); this. up. And. Down(b 2); } public void up. And. Down(Butterfly b){ b. move(10); b. move(15); b. land(); b. move(15); b. move(20); b. land(); } © Peter Andreae

Menu COMP 102: 120 • More defining methods with parameters • Methods that return

Menu COMP 102: 120 • More defining methods with parameters • Methods that return values Administration: © Peter Andreae

Another Java Program COMP 102: 121 • Design a Java program to measure reaction

Another Java Program COMP 102: 121 • Design a Java program to measure reaction time of users responding to true and false "facts". • Ask the user about a fact: "Is it true that the BE is a 4 Year degree? " • Measure the time they took • Print out how much time. • Need a class • what name? • Need a method • what name? • what parameters? • what actions? © Peter Andreae

Reaction. Time. Measurer COMP 102: 122 /** Measures reaction times for responding to true-false

Reaction. Time. Measurer COMP 102: 122 /** Measures reaction times for responding to true-false statements */ public class Reaction. Time. Measurer { /** Measure and report the time taken to react to a question */ public void measure. Reaction. Time() { // find out the current time and remember it // ask the question and wait for answer // find out (and remember) the current time // print the difference between the two times } } Write the method body in comments first, (to plan the method without worrying about syntax) Work out what information needs to be stored (ie, variables) © Peter Andreae

COMP 102: 123 Reaction. Time. Measurer /** Measure and report the time taken to

COMP 102: 123 Reaction. Time. Measurer /** Measure and report the time taken to react to a question */ public void measure. Reaction. Time() { Returns a very big integer ⇒ long (milliseconds since 1/1/1970 long start. Time = System. current. Time. Millis(); UI. ask. String("Is it true that the sky is blue? "); long end. Time = System. current. Time. Millis(); UI. printf("Reaction time = %d milliseconds n", (end. Time - start. Time) ); } } Just asking one question is not enough for an experiment. need to ask a sequence of questions. © Peter Andreae

Multiple questions, the bad way /** Measure and report the time taken to react

Multiple questions, the bad way /** Measure and report the time taken to react to a question */ public void measure. Reaction. Time(){ long start. Time = System. current. Time. Millis(); UI. ask. String( "Is it true that John Quay was the Prime Minister"); long end. Time = System. current. Time. Millis(); UI. printf("You took %d milliseconds n", (end. Time - start. Time) ); COMP 102: 124 Lots of repetition. But not exact repetition. How can we improve it? start. Time = System. current. Time. Millis(); UI. ask. String( "Is it true that 6 x 4 = 23"); end. Time = System. current. Time. Millis(); UI. printf("You took %d milliseconds n", (end. Time - start. Time) ); start. Time = System. current. Time. Millis(); UI. ask. String( "Is it true that summer is warmer than winter"); end. Time = System. current. Time. Millis(); UI. printf("You took %d milliseconds n", (end. Time - start. Time) ); } start. Time = System. current. Time. Millis(); UI. ask. String( "Is it true that Wellington’s population > 1, 000"); end. Time = System. current. Time. Millis(); UI. printf("You took %d milliseconds n", (end. Time - start. Time) ); © Peter Andreae

Good design with methods COMP 102: 125 • Key design principle: • Wrap up

Good design with methods COMP 102: 125 • Key design principle: • Wrap up repeated sections of code into a separate method, • Call the method several times: public void measure. Reaction. Time ( ) { this. measure. Question( "John ); Quay was the Prime Minister"); this. measure. Question( "6 x); 4 = 23"); this. measure. Question( “Summer ); is warmer than winter"); population > 1, 000 "); this. measure. Question( "Wellington’s ); } fact public void measure. Question ( String…… ){ long start. Time = System. current. Time. Millis(); UI. ask. String("Is it true that " ……… + fact ); long end. Time = System. current. Time. Millis(); UI. printf("You took %d milliseconds n", (end. Time - start. Time) ); } We need to parameterise the method © Peter Andreae

Improving Reaction. Time. Measurer (1) COMP 102: 126 public void measure. Reaction. Time() {

Improving Reaction. Time. Measurer (1) COMP 102: 126 public void measure. Reaction. Time() { this. measure. Question("John Quay was the Prime Minister"); this. measure. Question(“ 6 x 4 = 23"); this. measure. Question(“Summer is warmer than Winter"); this. measure. Question("Wellington’s population > 1, 000 "); } public void measure. Question(String fact) { long start. Time = System. current. Time. Millis(); UI. ask. String("Is it true that" + fact); long end. Time = System. current. Time. Millis(); UI. printf("You took %d milliseconds n", (end. Time - start. Time) ); } © Peter Andreae

Understanding Reaction. Time. Measurer COMP 102: 129 • What happens if we call the

Understanding Reaction. Time. Measurer COMP 102: 129 • What happens if we call the method on the object RTM 1: RTM 1. measure. Time(); public void measure. Reaction. Time(){ this: RTM- 1 this. measure. Question("John Quay was the Prime Minister"); this. measure. Question("6 x 4 = 23"); this. measure. Question(“summer is warmer than Winter"); this. measure. Question("Wellington’s population >1, 000"); The object the method was called on is copied to "this" place © Peter Andreae

COMP 102: 130 Understanding method calls public void measure. Question(String fact){ "John Quay is…"

COMP 102: 130 Understanding method calls public void measure. Question(String fact){ "John Quay is…" this: RTM-1 long start. Time = System. current. Time. Millis(); UI. ask. String("Is it true that " + fact); long end. Time = System. current. Time. Millis(); UI. printf("You took %d milliseconds n", (end. Time - start. Time) ); } © Peter Andreae

Understanding Reaction. Time. Measurer public void measure. Reaction. Time(){ COMP 102: 131 this: RTM-1

Understanding Reaction. Time. Measurer public void measure. Reaction. Time(){ COMP 102: 131 this: RTM-1 this. measure. Question("John Quay was the Prime Minister"); this. measure. Question("6 x 4 = 23"); this. measure. Question(“summer is warmer than Winter"); this. measure. Question("Wellington’s population > 1, 000"); © Peter Andreae

Understanding Reaction. Time. Measurer COMP 102: 132 New measure. Question worksheet: public void measure.

Understanding Reaction. Time. Measurer COMP 102: 132 New measure. Question worksheet: public void measure. Question(String fact){ " 6 x 9 = 54 " this: RTM-1 long start. Time = System. current. Time. Millis(); UI. ask. String("Is it true that " + fact); long end. Time = System. current. Time. Millis(); UI. printf("You took %d milliseconds n", (end. Time - start. Time) ); } Each time you call a method, it makes a fresh copy of the worksheet! © Peter Andreae

Understanding Reaction. Time. Measurer public void Measure. Reaction. Time(){ COMP 102: 133 this: RTM-1

Understanding Reaction. Time. Measurer public void Measure. Reaction. Time(){ COMP 102: 133 this: RTM-1 this. measure. Qn("John Quay was the Prime Minister"); this. measure. Qn("6 x 4 = 23"); this. measure. Qn(“summer is warmer than Winter"); this. measure. Qn(" Wellington’s population > 1, 000"); © Peter Andreae

Problem COMP 102: 134 • A good experiment would measure the average time over

Problem COMP 102: 134 • A good experiment would measure the average time over a series of trials • Our program measures and reports for each trial. • Need to add up all the times, and compute average: • problem: • Measure. Reaction. Time needs to add up the times • Measure. Question actually measures the time, but prints it out. • How do we get the time back from Measure. Question to Measure. Time? © Peter Andreae

Methods that return values COMP 102: 135 • Some methods just have "effects": UI.

Methods that return values COMP 102: 135 • Some methods just have "effects": UI. println("Hello there!"); UI. printf("%4. 2 f miles is the same as %4. 2 f kmn", mile, km); UI. fill. Rect(100, wd, ht); UI. sleep(1000); • Some methods just return a value: long now = System. current. Time. Millis(); double distance = 20 * Math. random(); double ans = Math. pow(3. 5, 17. 3); • Some methods do both: double height = UI. ask. Double("How tall are you"); Color col =JColor. Chooser. show. Dialog(UI. get. Frame(), "paintbrush", Color. red); © Peter Andreae

Defining methods to return values Improving Reaction. Time. Measurer: COMP 102: 136 make measure.

Defining methods to return values Improving Reaction. Time. Measurer: COMP 102: 136 make measure. Question return a value instead of just printing it out. public void measure. Reaction. Time() { long time = 0; time = time + this. measure. Question("John Quay was the Prime Minister"); time = time + this. measure. Question("11 x 13 = 143"); time = time + this. measure. Question(“Summer is warmer than Winter"); time = time + this. measure. Question(" Wellington’s pop > 1, 000 "); UI. printf("Average reaction time = %d millisecondsn", (time / 4)); } Specifies the type of value returned. . void means "no value returned" public long void measure. Question(String fact) { long start. Time = System. current. Time. Millis(); …… } © Peter Andreae

COMP 102: 137 Syntax: Method Definitions (v 3) /** Measure time taken to answer

COMP 102: 137 Syntax: Method Definitions (v 3) /** Measure time taken to answer a question*/ public long measure. Question ( String fact ){ long start. Time = System. current. Time. Millis(); : 〈Comment〉 public 〈Header〉 〈type〉 〈name〉 { } 〈Body〉 ( 〈parameters〉 〈type〉 ) 〈name〉 , © Peter Andreae

Defining methods to return values COMP 102: 138 If you declare that a method

Defining methods to return values COMP 102: 138 If you declare that a method returns a value, then the method body must return one! public long measure. Question(String fact) { long start. Time = System. current. Time. Millis(); String ans = UI. ask. String("Is it true that " + fact); long end. Time = System. current. Time. Millis(); return (end. Time start. Time) ; UI. printf("You took- %d millisecondsn" , (end. Time - start. Time) ); } New kind of statement Means: exit the method and return the value The value must be of the right type © Peter Andreae

COMP 102: 139 Returning values. • What happens if we call the method: RTM-1.

COMP 102: 139 Returning values. • What happens if we call the method: RTM-1. ask. Questions(); public void measure. Reaction. Time(){ long time = 0; this: RTM-1 0 time = time + this. measure. Question("John Quay was the Prime Minister"); time = time + this. measure. Question("6 x 4 = 23"); time = time + this. measure. Question(“summer is warmer than Winter"); time = time + this. measure. Question(“Wellington’s pop > 1, 000"); © Peter Andreae

COMP 102: 140 Returning values return value: public long measure. Qn(String fact){ "John Quay

COMP 102: 140 Returning values return value: public long measure. Qn(String fact){ "John Quay was" this: RTM- 1 long start. Time = System. current. Time. Millis(); " UI. ask. String("Is it true that " + fact); " long end. Time = System. current. Time. Millis(); return (end. Time - start. Time) ; } © Peter Andreae

COMP 102: 141 Returning values. • What happens if we call the method: RTM-1.

COMP 102: 141 Returning values. • What happens if we call the method: RTM-1. ask. Questions(); public void measure. Reaction. Time(){ this: RTM-1 0 long time = 0; time = time + this. measure. Question("John Quay was the Prime Minister"); time = time + this. measure. Question("6 x 4 = 23"); time = time + this. measure. Question(“summer is warmer than Winter"); time = time + this. measure. Question(" Wellington’s pop > 1, 000"); © Peter Andreae

Aside: Random numbers COMP 102: 142 • Math. random() computes and returns a random

Aside: Random numbers COMP 102: 142 • Math. random() computes and returns a random double • between 0. 0 and 1. 0 • To get a random number between min and max: • min + random number * (max-min) (50. 0 + Math. random() * 70. 0) gives a value between 50. 0 and 120. 0 • This is an expression: • can assign it to a variable to remember it • can use it inside a larger expression • can pass it directly to a method © Peter Andreae