1 Introduction to Computer Program Design COMP 102 2017 T1 .Peter Andreae ( “Pondy” ) Computer Science Victoria University of Wellington
2 COMP 102 Menu: Introductions What is COMP102 about?Where does COMP102 fit in your degree? Course organisation What to do NOW! Admin: Handouts: Course Outline Lecture slides 1 Switching to COMP112: see me after the lecture, outside lecture room
3 Introductions Course Organiser (Overall course management)Ian Welch Office: AM 403 Lecturer (Lectures) Peter Andreae (Pondy) Office: CO 336 Senior Tutor (Administrative issues regarding labs) Zarinah Amin Office: CO 252 Programmer Dr. Monique Damito to report problems: Tutors (Help in labs or via online help system) Range of Undergraduates and Graduates School Office (Forgotten passwords) CO 358
4 Essential Info: Lectures, Labs, Assigs, InfoLectures: Monday, Thursday, Friday, Memorial Theatre (SUMT228) Stream 1: 10am – 11am, (CRN 943) Stream 2: 12noon – 1pm, (CRN 28225) Same content. Please go to the CRN you enrolled in, (at least at the beginning). Labs: One hour session on Thursday or Friday One of the A choices One hour session on Tuesday (or Monday) One of the B choices Start this Thursday! Sign up at https://student-sa.victoria.ac.nz Assignments: weekly, starting next week Information: ecs.victoria.ac.nz/Courses/COMP102_2017T1, also accessible via Blackboard Mon Tue Wed Thu Fri 9 Lab B2 Assig due 10 LECTURE Lab B3 11 Lab B4 Lab A1 Lab A6 12 Lab B5 1 Lab B6 Lab A2 Lab A7 2 Lab B1 Lab A3 3 Lab B7 Lab A4 Lab A8 4 Lab B8 Lab A5 5 Tutorial Note: problems with MyAllocator, especially for Lab B’s
5 Computing is everywhereComputer based systems are everywhere user application programs – browsers, photo editors, chat programs social media and mobile phone apps,… computer games Information systems in commerce and business specialised applications – analysing gene data, X-rays, simulations controllers for device – cars, washing machines, TVs, DVD player, etc operating systems that run computers, cell phones, etc. network communication: internet connections, phone exchanges, fibre optics, cell phone systems, etc …. ⇒ Computing underlies almost all aspects of modern life
6 Computer Science Computer Science is the science of ComputingThe study of the computing processes that happen inside computers when they are working. How do we design, build, analyse systems that deal with information: text numbers graphics and video sound sensor and control signals ….
7 Computer Science QuestionsHow do you…. design a computer system to manage an organisation’s information? design an intelligent assistant for your phone that can talk with you? enable social interaction over communication networks send data securely and reliably over unreliable public networks? manage large teams of programmers building insanely complicated programs design algorithms that will create new visual effects for augmented reality applications design a database so that it is impossible to enter inconsistent data? design programming languages to make programming easier ensure that the computer program controlling a nuclear reactor or a spacecraft never makes a mistake? design a self-driving car that drives safely on city roads? make a safe encryption scheme for electronic commerce? determine whether some computation is tractable or even possible?
8 What is COMP 102? CS A first course in Computer ScienceComputer Graphics Software Engineering Network Engineering A required course for Electronic and Computer Engineering Human Genetics An important course for Information Systems Media Design A useful course for Everyone CS CGRA INFO NWEN ECEN SWEN MDDN
9 COMP 102 is not a Computer Science overviewWhy not? To understand the issues and principles of Computer Science, we need to understand and be able to talk about computation. Programming is about specifying the computation that a computer should do We need to be able to write, understand, think about, and analyse programs to address the issues of Computer Science Programming is fundamental to the engineering side of Computer Science.
10 What is COMP 102 about? COMP 102 is about learning the language and the ways of thinking required for programming in Computer Science, Software and Network Engineering etc. Programming is about designing new programs, applications, systems by writing the instructions to make a computer behave in the way we want it to. In COMP102, you will design and write lots of little programs for a wide variety of tasks. Gives 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,.
11 Goals of COMP102 By the end of COMP102 you will be able tounderstand, design, and construct small computer programs (in Java). ⇒ be able to use computers to solve new problems ⇒ be able to think in a new way about problems Note: We don’t assume you have done any programming. COMP102 starts from the beginning (more on this in a moment) Example programs: Bouncing ball simulator diagram editor photo manipulator little game
12 What does COMP102 cover? Focus of the course:Object Oriented programming and design. Programming with the Java programming language. Java is a widely used programming language Clean enough for learning to program Useful for real programming Strong enough for very large programs Practical programming, writing small programs. Testing and debugging. Principles of good design.
13 Is COMP102 For You? Required course for Computer Science, EngineeringUseful course for anyone who wants to be able to program. Women students do as well or better than men students. Not about using computers and applications software. Not an “easy credits” course for most people Involves higher level thinking skills than many students expect Key factors for success are logical/abstract thinking, being able to think about your own thinking processes problem solving, not memory attention to detail not getting behind Takes time! plan on around 10 hours / week Practical work is critical
14 Should you take COMP112 instead?COMP112: alternative to COMP102 for BE or BSc(COMP) Both courses let you proceed to COMP103 COMP 112 assumes programming experience: variables, loops, conditionals (if’s), input and output writing functions/procedures/methods with parameters lists or arrays little bit of event driven input, object oriented design doesn’t care what language you used COMP112 gives more breadth of coverage of Computer Science also involves more complex programming problems No programming experience COMP 102 COMP 103 Some programming experience eg level 3 NCEA DT programming standards COMP 112 You can’t do COMP102 and COMP112 at the same time!
15 Switching to COMP 112 If you have programming experiencecheck out what we expect at Come along to the COMP112 lectures: 1pm Wed in MCLT101 2pm Thu, Fri in SUMT228 Check out the first assignment in COMP112 See me after a lecture to get switched over Within the first two weeks Bring a change of course form from the science faculty office.
16 COMP 102 Background We assume you have used a computerWe 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 if you have done lots of programming, take COMP112 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.
17 Planning Ahead: If you are doing BE, or BSc (COMP), BSc (CGRA), or BDI minor then you should plan on taking COMP103 in Tri 2. If you are doing BE, or BSc (COMP or CGRA) Don’t forget the maths courses that you need for 2nd year! If you are doing BSc (CGRA) Don’t forget DSDN 132 You need a B- or better in COMP 102 to get in to COMP 103
18 Planning Ahead: MathematicsEngineering maths Mathematics maths BE SWEN: ENGR 121, 123 or MATH 161, STAT 193 BE NWEN: ENGR 121, 123 or MATH 161, 151, STAT 193 BE ECEN: ENGR 121, 122 or MATH 151, 142 BSc COMP: ENGR 121, 123 or MATH 161, STAT 193/MATH177 BSc CGRA: ENGR 121, 123, 122 or MATH 151, 142, 161 Which should you take?
19 Planning Ahead: MathematicsWhich 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, AS91578) and 3.7 (integration, AS91579) one of 3.5 (complex nos, AS91577) or 3.1 (conics, AS91573) or 3.3 (trigonometry, AS91575) or 3.13 (probability, AS91585) or 3.14 (probability distributions, AS91586)). At least 2 standards must be with grades of merit or excellence. If you want to switch
20 What to do NOW! 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 Details of course organisation tomorrow
21 Menu Introducing yourself More course details (FAST!)Programs and programming languages A first Java Program Reading: Text Book Chapter 1 Announcements: Sign up for a lab session! Labs start Today (11am for A1) 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. Trouble with passwords? Go to school office: CO 358
22 Google is coming to VUW! Next Wendesday and ThursdayFREE Pizza, Prizes and Q&A! Wednesday 15th March: Inclusion in Hacking Reduce bias and promote inclusion to create impact and innovation. Come ready for an interactive learning experience with Googlers that will help you contribute to an inclusive culture at university and beyond where all of you can thrive. 5pm - 7pm: AM103, Alan MacDiarmid Building Thursday 16th March Life at Google Talk + Live Technical Interview 5:30pm - 8pm, MCLT101,
23 Course Organisation All the details are in the course outline: handouton the course web page: Optional Tutorial/Review Sessions Tue 5-6, KK 202 from 2nd? or 3rd week, 1st year help sessions: Mon, Wed 5-7, AM106
24 Course Web Site An essential resource for the course:(also accessible via link on BlackBoard) Course information, announcements, handouts, videos Lab Assignment details (times, dates, handouts, files, ...) Forum, for questions and discussion Info about doing work at home. Java documentation Other useful links Primary administrative communication channel.
25 Lab assignments This is where your learning happens!Nine assignments (roughly weekly), hand out: Thursday due: 9am Thursday (a week later) (except #4 & #10) 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 (A) Thurs/Fri (to get started) Second session (B) Tues (to get more help) Further work required: expect 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.
26 Course Organisation Help Desk Study groupsOnline help: Forum for general questions; /web form for questions about your code. Help Desk: Tutors available at various times: TBA (12-1?) Study groups We will facilitate organising study groups and tutored help sessions First year engineering/CompSci tutorials/help sessions Excellent way of helping your learning Science and Engineering Faculty Awhina programme: support for Maori and Pacific Nations students Women students support group.
27 Text Book and Handouts Text BookJava Foundations Lewis, DePasquale, Chase Same as for COMP103. [also OK: Java Software Solutions (6th 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! Handouts Lecture slides, Assignments Handed out in class. On COMP102 web page.
28 Tests and Exams Terms Test 1: Terms Test 2: Exam: 15%Monday 3 April or 6-7 pm (To be confirmed) NOT in lecture time! Terms Test 2: Monday 15 May or 6-7 pm(To be confirmed) Exam: 50% Date tba (between 9 June and 12 July)
29 Assessment Mandatory Course Requirement: Final Grade:Submit reasonable attempts ( at least D) for at least 7 of assignments. Final Grade: Assignments: 20% Terms Test 1: 15% (mark boosted to exam mark, if better) Terms Test 2: 15% (mark boosted to exam mark, if better) Exam: 50% To pass the course, you must: Satisfy the Mandatory Requirement. Get overall grade of C- or better. Need B- or better to get into COMP103
30 Withdrawal dates Early withdrawal with refund: up do Fri 17 Marchno consequences to early withdrawal Standard withdrawal without refund: up to Friday 19 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 19 May Requires permission of Associate Dean Normally given only when special circumstances arise after deadline.
31 Plagiarism (Cheating)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 COMP102: 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!
32 Cheating in the assignments.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.
33 Lab Facilities All scheduled labs are in CO219/238Can 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!
34 Where to go for Help Depends on the kind of help neededCourse organiser / Lecturer, Senior Tutor, tutors (in labs or helpdesk only!) Forum (via website) On-line help system (via website) Help desk (CO 242b?) ECS School Office: CO 358 Student Services: Science Faculty office: Science/Engineering/Arch&Des Awhina programme The Web
35 What is a Program 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: Low level, High level, Specialised
36 Machine Language What the computer can understandDifferent for each computer Very detailed, low-level control of the computer Horrible to read copy the contents of memory location 143 into register 1. : 000XX00X 0X00XXXX 0XX0X00X 00XXX0X0 00X0X00X X0XX0X0X add the contents of memory location 116 to the contents of register 1. Pattern of bits controls the switches that operate the CPU copy the contents of register 1 to memory location 181.
37 High Level Programming LanguagesDesigned for people to use Designed to be translated into machine language compiled (translated all at once), or interpreted (translated one step at a time), or compiled to an intermediate language, then interpreted Must be Precise: no ambiguity about what to do Expressive: must be able to specify whatever you want done. Readable: People must be able to read the instructions. Translatable: able to be translated into machine language Concise: not “long-winded” or redundant FORTRAN LISP Algol COBOL Basic C Pascal Simula Modula PHP Javascript Smalltalk ML Ada C++ Eiffel Prolog Haskell Miranda Java C# Python Scratch GameMaker Alice
38 Programming LanguagesDifferent languages support different “paradigms”: (ways of designing programs) imperative, object-oriented, functional, logic programming, ... Object Oriented programming languages: Organise program around Classes (types) of objects Each class of objects can perform a particular set of actions Most instructions consist of asking an object to perform one of its actions
39 Menu Introducing yourself Getting Help NCEA vs universityDesigning a Java program Announcements: Can’t find a lab slot that works? Class rep: vote on Monday. Put/Read candidate statements on the forum Lost property from labs: ID cards, USB sticks school office General Lost Property Student Union office
40 Getting Help: Inside COMP 102Ask 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) to can include your code – only visible by staff and tutors Go to the Tutorials on Tuesdays 5-6, Mondays/Wednesdays 5-7 Go to the help desks.
41 NCEA vs University 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 focusses on getting Achieved; Excellence is very difficult. if you have Achieved, may not be worth trying harder. Uni focusses on grades; A’s are more achievable Just passing is not enough It’s worth doing more because it will increase your grade.
42 Java A high-level Object-Oriented programming languageDesigned by Sun Microsystems, early-mid 1990's. Widely used in teaching and industry Related to C++, but simpler. Similar to C#. Good for interactive applications. Extensive libraries of predefined classes to support, UIs, graphics, databases, web applications, ... Portable between kinds of computers.
43 A Java Program import ecs100.*;/** Program to compute the average of a sequence of numbers */ public class MeanFinder { public MeanFinder () { UI.addButton("Compute Mean" , this::doFindMean); } /** Ask for sequence of numbers and print the mean */ public void doFindMean () { ArrayList
44 A Java Program import ecs100.*;/** Program to compute the average of a sequence of numbers */ public class MeanFinder { public void findMean () { double total= 0; int count =0; ArrayList
45 Learning to Program in JavaWhat’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.
46 Constructing Programs in JavaSpecification Design Edit typing in the Java code syntax errors Compile Translating to executable instructions logic errors Run Testing the program to see that it works
47 A first Java Program Task: Write a temperature conversion program: C ⇔ F 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 calculate action: Ask user for the Fahrenheit value to be converted Print Celsius value: Calculate Celsius value out of given value (F-32.0)*5.0/9.0 Print out the answer Two Actions ⇒ two buttons
48 Designing the Java programStep 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 a constructor to set up the interface 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
49 Writing the Java code Comments Keywords Identifiers Strings Typesimport ecs100.*; /** Program for converting between temperature scales */ public class TemperatureCalculator{ /** Constructor: Set up interface */ public TemperatureCalculator (){ UI.addButton("Formula", this:: printFormula); UI.addButton("F->C", this:: doFahrenheitToCelsius); } /** Print conversion formula */ public void printFormula ( ) { UI.println("Celsius = (Fahrenheit - 32) *5/9"); /** Ask for Fahrenheit and convert to Celsius */ public void doFahrenheitToCelsius(){ double fahrenheit = UI.askDouble("Farenheit:"); this. convertToCelsius(fahrenheit); /** Print Fahrenheit temperature as Celsius */ public void convertToCelsius(double temp){ double celsius = (temp ) * 5.0 / 9.0; UI.println(temp + " F -> " + celsius + " C"); Comments Keywords Identifiers Strings Types Numbers Operators Punctuation I have chosen to split into two separate methods. Could have just one bigger method.
50 Elements of the programProgram Structure: Import list the "libraries" you will use (We always use ecs100, 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. Constructor Called when object is created Typically sets up the user interface (in one-class programs) Methods Main elements of a class Each method describes an action that objects of this class can perform
51 Elements of the programComments 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
52 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"); this.printCelsius(fahrenheit); UI.drawRect(100, 200, 50, 75); UI.addButton(“Draw", this::doDraw); 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.askDouble(“Fahrenheit:");
53 BlueJ BlueJ 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 BlueJ
54 Compiling and Running Step 4: CompilingIf 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 BlueJ makes this process easier Let’s do it…
55 Compiling and Running Step 4: CompilingIf 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 BlueJ makes this process easier Step 5: Running and Testing Must run the program and test it on lots of different input. BlueJ makes it easy to run individual methods.
56 Using BlueJ for Java ProgramsSimple use of BlueJ for simple programs: Edit the class file(s) to define the methods Compile the class Create an object of the class right click on the rectangle representing the class select “new…..” ⇒ a red square representing the object Call methods on the object right click on the square representing the object select the method.
57 Menu More details about the Java Program Reading: AnnouncementsSemantics (meaning) and Syntax (grammar rules) Methods Statements Variables, Types, Assignment, Values and Expressions Reading: L-D-C: Chapter 2 Announcements Labs: how many need to sign up yet? Class Rep.
58 Class Representative Elijah-Blue Simonson: (first year studying a BE(Hons) majoring in Software Engineering) I have had a passion towards computers for many years now. I am enthusiastic about this course and want to allow everyone to get the best experience that they can have, I am willing to offer my advice to people during my free time and will ensure that Pondy knows of any major issues that are occurring for us the students.. Kelly Archer (first year student studying Computer Science and Theatre) I'm a great listener and can communicate your ideas effectively as a link between our class and our lecturer. I'm always available to listen and give advice but if I don't know I am more than happy to help find the best answer. Maisie Embleton (first year student hoping to major in Psychology and Computer Science) I recently moved down from Auckland and I really love cats. I am always ready to listen to any issues, thoughts or questions you may have and would do my very best to respectively help or answer. I would also do my very best to communicate ideas, provide feedback to, and between, you guys and Pondy! Vishal Ramanlal I am the 6 foot, black bearded dude with a great fresh trim. Vote for me and I'll give you a hi-five. Nicholas Bell (a second year, so I already know my way around) I communicate well with both lecturers and students. I'm happy to help with any problems you might be having with the course, or if you're not sure about anything at uni. I changed major to comp sci this year, so I can also give some advice on what to look for in a major, if you're unsure. P.S. Will bring lollies to lectures.
59 Temperature Converter (again)import ecs100.*; /** Program for converting between temperature scales */ public class TemperatureCalculator{ /** Constructor: Set up interface */ public TemperatureCalculator (){ UI.addButton("Formula", this:: printFormula); UI.addButton("F->C", this:: doFahrenheitToCelsius); } /** Print conversion formula */ public void printFormula ( ) { UI.println("Celsius = (Fahrenheit - 32) *5/9"); /** Ask for Fahrenheit and convert to Celsius */ public void doFahrenheitToCelsius(){ double fahrenheit = UI.askDouble("Farenheit:"); this. convertToCelsius(fahrenheit); /** Print Fahrenheit temperature as Celsius */ public void convertToCelsius(double temp){ double celsius = (temp ) * 5.0 / 9.0; UI.println(temp + " F -> " + celsius + " C");
60 Writing your own programsHow? Use other programs as models, and then modify Very useful strategy Lectures have examples that you can use as models for your assignment programs
61 A new program Calculator to convert inches to centimetersimport ecs100.*; /** Program to convert inches to centimeters */ public class TemperatureCalculator{ public void doFahrenheitToCelsius(){ double fahrenheit = UI.askDouble("Farenheit:"); this.convertToCelsius(fahrenheit); } public void convertToCelsius(double temp){ double celsius = (temp – 32.0) * 5.0 / 9.0; UI.println(temp + " F -> " + celsius + " C");
62 Writing your own programsHow? Use other programs as models, and then modify Very useful strategy BUT It can be hard to work out how to modify It is very limiting Need to understand the language ⇒ vocabulary ⇒ syntax rules ⇒ meaning (“semantics”)
63 Syntax rules: Program structureFirst version import ecs100.*; import java.awt.Color; 〈import statements〉 public class 〈classname〉 { 〈constructor description〉 〈method description〉 Comments can be added anywhere }
64 Comments Three kinds of comments: Documentation commentsTop of class, Before each method Three kinds of comments: Documentation comments eg /** Program for converting between temperature scales */ end-of-line comments eg double celsius = (fahren – 32.0) * 5.0 / 9.0; // compute answer anywhere comments eg /* double fahren = celsius * 9 / ; UI.println(celsius + “C is " + fahren + " F"); */ /** 〈text of comment〉 */ at end of any line // 〈text of comment〉 multi-line, or middle of line, or … /* 〈text of comment〉 */
65 Constructor Definitions/** Constructor: Set up interface */ public TemperatureCalculator (){ UI.addButton("Formula", this :: printFormula); UI.addButton("F->C", this :: doFahrenheitToCelsius); } instructions to perform when creating a new object 〈Doc Comment〉 〈Header〉 〈Body〉 { } public ( ) 〈class-name〉
66 Method Definitions 〈Doc Comment〉 〈Header〉 〈Body〉 { } public void ( )/** Print out the conversion formulas */ public void printFormula ( ) { UI.println("Celsius = (Fahrenheit - 32) *5/9"); } instructions to perform this action 〈Doc Comment〉 〈Header〉 〈Body〉 { } public void ( ) 〈name〉 〈parameters〉 Specifying the information the action needs. May be empty
67 “Statements” (instructions)(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.
68 Method Calls Method call Statement: Meaning of Statement:/** Print out the conversion formulas */ public void printFormula(){ UI.println( "Celsius = (Fahrenheit - 32) *5/9" ); } Method call Statement: who what ( data to use ) ; UI println ( “Celsius = (Fahren…” ) ; Meaning of Statement: Tell the object to perform the method using the argument values provided 〈object〉 . 〈methodname〉 ( 〈arguments〉 ) ;
69 Objects and their methods in JavaWhat objects are there? Predefined eg: UI a "User Interface" window with several panes initialize() quit() addButton(…) println(….) drawRect(…) clearGraphics(), askDouble(…) askString(…) Math methods for mathematical calculations random( ), sin(…) System representing the computer system currentTimeMillis( ) Others this The object(s) defined by this class in your program New objects that your program creates Some method calls return a value
70 Values / Data There are lots of different kinds ("Types") of values:Numbers Integers ( int or long) real numbers ( double or float ) e-34 … Characters ( char ) 'X' '4' Text ( String ) " F -> " Colours ( Color ) Color.red Color.green Methods this::doFahrenheitToCelsius Other Objects
71 Menu Variables, assignment, parametersUI class and using documentation Programs with Graphical output [L-D-C: Appendix F] Administration: Lost a textbook in the Hub?
72 Assignment 1 Calculator programsPrograms 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.
73 Variables A variable is a place in memory that can hold a value./** Print out the conversion formula (version 2) */ public void printFormula () { String formula; formula = "Celsius = (Fahrenheit - 32) *5/9" ; UI.println( formula ); } 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. 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) " " Use a variable whenever you need the computer to remember something temporarily. Asking for a place got to here
74 Assignment Statements/** Print out the conversion formulas (version 2) */ public void printFormula () { String formula; formula = "Celsius = (Fahrenheit - 32) *5/9" ; UI.println( formula ); } Assignment Statement: where = what ; name-of-place = specification-of-value ; formula = " Celsius = (Fahrenheit - 32) *5/9" Meaning: Compute the value and put it in the place " " Putting a value into a variable 〈variable〉 = 〈expression〉 ;
75 Expressions Expressions describe how to compute a value./** Convert from fahrenheit to Celsius */ public void doFahrenheitToCelsius(){ double fahrenheit = UI.askDouble("Fahrenheit:" ); double celsius = (fahrenheit – 32.0) * 5.0 / 9.0; UI.println(fahrenheit + “F is " + celsius + “ C"); } Expressions describe how to compute a value. Expressions are constructed from values variables operators (+, -, *, /, etc) method calls that return a value sub-expressions, using (… ) … Version 2: combined into a single method that asks, computes and prints. + for Strings: "concatenates" the Strings
76 Method Calls and variables: a metaphorMethod Definition: Like a pad of worksheets public void doFahrenheitToCelsius(){ double fahrenheit = UI.askDouble("Fahrenheit:"); double celsius = (fahrenheit – 32) * 5 / 9; UI.println(fahrenheit + “F is " + celsius + “ C"); } Calling a Method: tempCalc1.fahrenheitToCelsius(); ⇒ get a “copy” of the method worksheet ⇒ perform each action in the body. ⇒ throw the worksheet away (losing all the information on it) public void doFahrenheitToCelsius(){ double fahrenheit = UI.askDouble("Fahrenheit:"); double celsius = (fahrenheit – 32.0) * 5.0 / 9.0; UI.println(fahrenheit + “ is " + celsius + “ C"); } Fahrenheit: 86 86.0F is 30.0C 86 0 30 0
77 Method Definitions: Parameters/** Convert from fahrenheit to centigrade */ public void printCelsius(double temp){ double celsius = (temp – 32.0) * 5.0 / 9.0; UI.println(temp + " F -> " + celsius + " C"); } A parameter specifies the type of a value the method needs a name for the place where the value will be put when the method is called (a kind of variable, but special) Parameters are in defined in the headers of method definitions
78 Method Calls Method Definition: Like a pad of worksheetspublic void printCelsius(double temp){ double celsius = (temp – 32.0) * 5.0 / 9.0; UI.println(temp + “ F -> " + celsius + “ C"); } Calling a Method: tempConv1.printCelsius(86); ⇒ get a “copy” of the method worksheet ⇒ copy the argument(s) into the parameters(s) ⇒ perform the actions in the body. public void printCelsius(double temp){ double celsius = (temp – 32.0) * 5.0 / 9.0; UI.println(temp + “ F -> " + celsius + “ C"); }
79 Summary of Java program structureA Class specifies a type of object TemperatureCalculator.class describes TemperatureCalculator objects A Class contains a constructor Constructor specifies what to do when objects are created A Class contains a collection of methods Each method is an action the objects can perform. TemperatureCalculator objects can do celsiusToFahrenheit, fahrenheitToCelsius, printFormula If you have an object, you can call its methods on it. A constructor/method definitions contains statements Each statement specifies one step of performing the action Method call statements Declaration and Assignment statements
80 What can the UI do? UI is a predefined object Has methods fortext input from the user eg UI.askString("What is your name?"); UI.askDouble ("How tall are you") ; text output eg UI.println(" * " + name + " * " ); graphical output eg UI.drawRect(100, 100, 300, 150); making buttons, sliders, etc eg UI.addButton("Quit", UI::quit); How do you find out about all the methods? How do your find out what arguments you need to provide?
81 Read the Documentation!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 Tailored for Comp 102 Includes documentation of the ecs100 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.
82 Some UI methods Text: Graphics: UI.clearText()UI.print(anything ) UI.println(anything ) UI.printf( format-string, values…) UI.askString(prompt-string ) UI.askToken(prompt-string ) UI.askDouble(prompt-string ) UI.askInt(prompt-string ) UI.askBoolean(prompt-string ) Graphics: UI.clearGraphics() UI.setColor(color ) UI.setLineWidth(width ) UI.drawRect(left, top, wd, ht ) UI.fillRect(left, top, wd, ht ) UI.drawOval(left, top, wd, ht ) UI.fillOval(left, top, wd, ht ) UI.drawLine(x1, y1, x2, y2 ) UI.drawImage(file, left, top ) …… Eg: Color.red
83 Lollipop program Design: Must work out the coordinates: x(300) (200) x ≈ 700 Design: Method drawLollipop(): set line width to 10 draw line set line width back to 1 set color to red fill oval Must work out the coordinates: line: oval: y ≈500
84 Menu Reflection.txt Designing Methods with parametersMethods that call other methods in the same program Administration: Today is the deadline for adding or dropping with refund Online help: forum vs /web form Working together.
85 Programs with graphics outputWrite a program to draw a lollipop: Design What shapes can we draw? UI has methods to draw rectangles, ovals, lines, arcs,… ⇒ Draw one thick black line one red oval, 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. (0,0) y x Shapes are drawn on top of previous shapes Coordinates measured from left and top
86 Writing the program Need import statementsNeed a class (with a descriptive comment) Need a constructor Need a method (with a descriptive comment) import ecs100.*; import java.awt.Color; /** Draws little shapes on the graphics pane */ public class Drawer { /** Constructor: Set up interface */ public Drawer() { UI.addButton("Draw it", this::drawLollipop); } /** Draw an red lollipop with a stick */ public void drawLollipop() { // actions Button that will call the drawLollipop method of this class Write the method body as comments first
87 Writing the program: using commentsimport ecs100.*; import java.awt.Color ; /** Draws little pictures on the graphics pane */ public class Drawer { public Drawer() { UI.addButton("Draw it", this::drawLollipop); } /** Draw an red lollipop on a stick */ public void drawLollipop() { // set line width to 10 // draw line (300,200) to (300, 400) // set line width to 1 // set color to red // fill 80x80 Do it in BlueJ! Now express each comment in Java (look up documentation as necessary)
88 Writing the program import ecs100.*; import java.awt.Color ; /** Draws little pictures on the graphics pane */ public class Drawer { public Drawer() { UI.addButton("Draw it", this::drawLollipop); } /** Draw a lollipop */ public void drawLollipop() { UI.setLineWidth(10); // set line width to 10 UI.drawLine(300, 200, 300, 400); // draw line UI.setLineWidth(1); // set line width back to 1 UI.setColor(Color.red); // set color to red UI.fillOval(260, 160, 80, 80); // draw blob Now compile and run the program
89 A model/metaphor for the computerIf 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 Alzheimer's – only remembers what he writes down with a clipboard for the worksheets with the instructions he is currently working on looking at the back of the UI window which he can write/paint on, but the writing/painting only appears on the outside – he can't see what he has written/drawn can see a stream of characters that the user types on the keyboard
90 Lollipop Drawing programimport ecs100.*; import java.awt.Color ; /** Draws little pictures on the graphics pane */ public class Drawer { /** Constructor: Set up the interface with one button */ public Drawer() { UI.addButton("Draw it", this::drawLollipop); } /** Draw a lollipop */ public void drawLollipop() { UI.setColor(Color.black); // set color to black UI.setLineWidth(10); // set line width to 10 UI.drawLine(200, 300, 200, 400); // draw line UI.setLineWidth(1); // set line width back to 1 UI.setColor(Color.red); // set color to red UI.fillOval(260, 160, 80, 80); // draw blob
91 Improving the design This program is very inflexible: What ifWe 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
92 Move or resize the Lollipop.import ecs100.*; import java.awt.Color ; /** Draws little pictures on the graphics pane */ public class Drawer { /** Constructor: Set up the interface with one button */ public Drawer() { UI.addButton("Draw it", this::doDrawLollipop); } /** Draw a lollipop */ public void doDrawLollipop() { UI.setColor(Color.black); // set color to black UI.setLineWidth(10); // set line width to 10 UI.drawLine(300, 200, 300, 400); // draw line UI.setLineWidth(1); // set line width back to 1 UI.setColor(Color.red); // set color to red UI.fillOval(260, 160, 80, 80); // draw blob Move it left Move it down Change blob size
93 Improving the design 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.
94 Values to specify lollipop & sticksize x stick
95 Improving the program: constantsimport ecs100.*; import java.awt.Color; /** Draw a lollipop with a stick */ 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 = ; // length of lollipop stick public Drawer() { UI.addButton("Draw it", this::doDrawLollipop); } /** Draw a lollipop */ public void doDrawLollipop() { UI.setLineWidth(size/8.0); UI.drawLine(x, y, x, y+stick); UI.setLineWidth(1); UI.setColor(Color.red); UI.fillOval(x-size/2.0, y-size/2.0, size, size); Easy to change: one place! x size y stick
96 Syntax rules: Program structure2nd version 〈import statements〉 public class 〈classname〉 { Defining a constant 〈constant definition〉 public static final 〈constructor description〉 〈type〉 〈name〉 = 〈value〉 ; 〈method description〉 }
97 Improving the program: more namespublic 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 /** Constructor: Set up the interface with one button */ public Drawer() { UI.addButton("Draw it", this::doDrawLollipop); } /** Draw a lollipop */ public void doDrawLollipop() { UI.setLineWidth(10); UI.drawLine(x, y, x, y+stick); UI.setLineWidth(1); UI.setColor(Color.red); UI.fillOval(x-size/2.0, y-size/2.0, size, size); Still have a problem: What do these expressions mean?
98 Values to specify lollipop & sticktop left y size x stick bot Useful to have more named values!
99 Improving the program: variablespublic 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 public Drawer() { UI.addButton("Draw it", this::doDrawLollipop); } /** Draw a lollipop */ public void doDrawLollipop() { double left = x – size/2.0; // left of lollipop double top = y – size/2.0; // top of lollipop double bot = y + stick; // bottom of stick UI.setLineWidth(10); UI.drawLine(x, y, x, bot); UI.setLineWidth(1); UI.setColor(Color.red); UI.fillOval(left, top, size, size);
100 Principle of good designUse 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.
101 Even better design: parametersEvery 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 drawRect? drawRect has four parameters: Definition of drawRect: public void drawRect(double left, double top, double wd, double ht) {……} Calling drawRect: UI.drawRect(200, 150, 50, 80), ⇒ drawRect can make many different rectangles. Why can't we do that with lollipop? In the library files Parameters In our program Arguments
102 Improving the program: using parameters/** Draw a lollipop at (300, 180), asking the user for its size */ public void doDrawLollipop() { double size = UI.askDouble("Diameter:"); double stickHeight = UI.askDouble("Stick height"); this.drawLollipop(300, 180, size, stickHeight); } public void drawLollipop(double x, double y, double size, double stick) { double left = x – size/2.0; // left of lollipop double top = y – size/2.0; // top of lollipop double bot = y + stick; // bottom of stick UI.setLineWidth(10); UI.drawLine(x, y, x, bot); UI.setLineWidth(1); UI.setColor(Color.red); UI.fillOval(left, top, size, size); x size y stickHeight Parameters Special variables which are given values each time the method is called. Body of method can use the values in the parameters
103 Syntax: Method Definitions (v2)/** Draw a lollipop on a stick */ public void drawLollipop(double x, double y, double size, double stick ){ double left = x – size/ 2.0; : 〈Comment〉 〈Header〉 〈Body〉 { } public void 〈name〉 ( 〈parameters〉 ) 〈type〉 〈name〉 How do you call a method with parameters from BlueJ? ,
104 Method Calls with parametersMethod Definition: Like a pad of worksheets Calling a Method: this.drawLollipop(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) public void drawLollipop( double x, double y, double size, double stick){ double left = x – size / 2.0; double top = y – size / 2.0; : UI.fillOval(left, top, size, size); } 300 0 100 0 75 0 95 0 public void drawLollipop( double x, double y, double size, double stick){ double left = x – size / 2.0; double top = y – size / 2.0; : UI.fillOval(left, top, size, size); }
105 Calling drawLollipop public class Drawer { public void doDrawLollipops() { double diam = UI.askDouble("diameter:"); this.drawLollipop(300, 180, diam, 200); this.drawLollipop(50, 60, diam/2.0, 90); this.drawLollipop(400, 100, diam, 70); } /** Draw a lollipop */ public void drawLollipop(double x, double y, double size, double stick) { double left = x – size/2.0; // left of lollipop double top = y – size/2.0; // top of lollipop double bot = y + stick; // bottom of stick UI.setLineWidth(10); UI.drawLine(x, y, x, bot); UI.setLineWidth(1); UI.setColor(Color.red); UI.fillOval(left, top, size, size);
106 Principle of good designParameterising 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
107 Arithmetic in Java normal arithmetic operators: + – * and /on doubles, operators work as expected length / => 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 % gives the remainder 15 / 4 => % 4 => / 30 => numDoors / numWalls => * numDoors / numWalls => length: numDoors: numWalls:
108 PaintCalculator program (live programming)import ecs100.*; import java.awt.Color; public class PaintCalculator{ public static final double DOOR_AREA = 1.7; public static final double LITRES_PER_SQM = 0.23; public static final double DOLLARS_PER_LITRE = 8.0; public PaintCalculator(){ UI.initialise(); UI.addButton("Calculate Paint", this::doCalculatePaint); UI.addButton("Quit", UI::quit); } public void doCalculatePaint(){ double wallLength = UI.askDouble("wall length"); // ask for wall length double wallHeight = UI.askDouble("wall height"); // ask for wall height double wallArea = wallLength * wallHeight; //calculate wall area int numDoors = UI.askInt("number of doors"); //ask doors double litresOfPaint = (wallArea - (numDoors * DOOR_AREA)) * LITRES_PER_SQM;//calculate paint area and # of litres UI.printf("Litres of paint needed: %.2f litres\n", litresOfPaint ); //print out paint UI.printf("Cost: $%.2f\n", (litresOfPaint * DOLLARS_PER_LITRE)); // print out the cost
109 Programs with Choice Booleans, COMP 102 #8 2016Note, this took one and a half lectures
110 Menu Programs with Choice LDC 4.2 if ( … ) { … } else { … }Boolean Expressions LDC 4.1, 4.3 Admin: Forum and notifications java on your computer, ecs100.tmpl study groups submission deadline and model solutions reminder about tutorial
111 Where have we been? 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
112 Programs that make decisionsPrograms that perform the same action every time are boring! You can vary the action in a program By clicking different buttons By getting input from the user: String name = UI.askString("name:"); : UI.printf("Hello %s, how are you?", name);
113 Programs that make decisionsBut 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.
114 Decisions in Java Java has an if … else … statement:Can do an action only in some circumstances: if ( countTimes > 10 ) { UI.clearGraphics(); this.drawBoard(10, 10, 100); } Can choose between different actions: if ( userChoice.equals(“Yes" ) ){ UI.drawImage("Nod.png", left, top); else { UI.drawImage(“Shake.png“, left, top);
115 Java: if and if … else LDC 4.2Two 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 〉 ) { 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.
116 boolean valued expressionif … vs if … else … if ( boolean valued expression ) { statements } else { statements }
117 Method with a condition/** Ask for amount and currency; print note if –ve, print value.*/ public void convertMoney( ) { ; double amount = UI.askDouble("Enter amount $NZ"); if ( amount < 0 ) { UI.println("Note: you have entered a debt!"); } String currency = UI.askString ("Enter currency (US or Aus)"); if ( currency.equals("US") ) { UI.printf("$NZ%.2f = $US%.2f\n", amount, (amount * 0.668)); else { UI.printf("$NZ%.2f = $AUS%.2f\n", amountt, (amount * 0.893)); Like println, but can control the format: %.2f floating point, 2dp %d integer %s string \n new line What is printf?
118 Multiway choice: if … else if … else if …Can put another if statement in the else part: if (〈condition1 〉 ) { 〈actions to perform if condition1 is true〉 : } else if (〈condition2 〉 ) { 〈actions to perform if condition 2 is true (but not condition 1) 〉 else if (〈condition3 〉 ) { 〈actions to perform if condition 3 is true (but not conditions 1, 2)〉 else { 〈actions to perform if other conditions are false〉
119 Example with multiway choicepublic void convertMoney( ) { double amount = UI.askDouble("Enter amount"); if (amount < 0 ) { UI.println("Note: you have entered a debt!"); } String currency = UI.askString("Enter currency (US or Aus)"); if (currency.equals("US") ) { UI.printf("$NZ%.2f = $US%.2f%n", amount , amount * 0.668); else if ( currency.equals("Aus") ) { UI.printf("$NZ%.2f = $AUS%.2f\n", amount , amount * 0.893); else { UI.printf("I cannot convert to %s currency%n", currency);
120 Example 2 with multi way choicepublic void printPay( 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 = $ %.2f %n", pay); else if ( day == 6 ) { pay = pay * 1.5; UI.printf("Pay = $ %.2f ( time-and-a-half) %n", pay); else { pay = pay * 2; UI.printf("Pay = $ %.2f ( double-time) %n", pay);
121 Boolean expressions LDC 4.1What 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") boolean variables: outlineOnly [ if declared boolean outlineOnly; ] logical operators: !, &&, || (not, and, or) ( x > 0 && x < 7 && outlineOnly ) ( month.startsWith("Ju") || month.equals("May") ) ( ! fileModified || ! (cmd.equals("exit")) ) more methods on String equalsIgnoreCase("John”) startsWith(“Ab”) endsWith(“ies”)
122 Writing Boolean expressionsMostly, 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") → false “NZ".equalsIgnoreCase(“nz") → true
123 Boolean Variables 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 printSteps = UI.askBoolean("Print all steps?"); : if ( printSteps ) UI.println("Processed input"); UI.println("Computed Statistics");
124 Compound Boolean expressions: operatorsUsing logical operators: Not: ! eg ( ! currency.equalsIgnoreCase(“US") ) And: && eg ( x > 0 && x < 7 && outlineOnly ) 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.startsWith("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: ( ! fileModified || ( cmd.equals("exit") && lastSaveTime > 5000) ) safest to use lots of (…)
125 Traps with Boolean expressionsWhen 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: if ( ! (count == 0) ) { … OR if ( count != 0 ) { …
126 Menu Creating and using objects inside a program AdminAssig 2 due on Thursday at 9am Submit .java files, not .class files Help desks start this week: Wed 12-1, 3-4, Thu 11-1. Online help: to and attach your java files The optional lab time for women students only starts this friday: 12-1. this is in addition to the regular lab sessions with the tutors.
127 Object oriented programmingKey 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 BlueJ. not standard, and not a general solution
128 Objects 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. (TemperatureConverter, Drawer)
129 Examples of objects Butterfly program CartoonFigure programEach 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() CartoonFigure program Each cartoon figure is represented by an object which stores the state of the cartoon figure (image, position, direction facing, smile/frown). CartoonFigure objects have methods walk(double dist) smile() frown() lookLeft() lookRight() speak(String words) think(String words)
130 Using objects If the variable bf1 and bf2 contained Butterfly objects, you could do: public void showButterflies(){ Butterfly bf1 = ????? Butterfly bf2 = ????? bf1.move(10); bf2.move(20); bf1.land(); bf1.move(5); } Problem: How do you get a Butterfly object into the variables? Nothing new here: Just standard method calls!
131 Creating Objects Need to construct new objects:New kind of expression: new Butterfly bf1 = new Butterfly( … … ) 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 Calling the constructor 100, 300 Creates a new object, which is put into bf1
132 Creating Objects: new Calling a constructor:Butterfly b1 = new Butterfly(100, 300); UI.setColor( new Color(255, 190, 0) ); Calling a constructor: new ( a keyword) Butterfly ( 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 new 〈Class name〉 ( 〈arguments〉 )
133 Reading DocumentationDocumentation of a class: 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 Bluej lets you see the documentation of your classes
134 Example: Butterfly Grove programpublic class ButterflyGrove{ /** A grove of Butterflies which fly around and land */ public void oneButterfly(){ Butterfly b1 = new Butterfly(50, 20); b1.move(5); b1.move(10); b1.move(15); b1.move(11); b1.move(12); b1.move(13); b1.move(14); b1.move(16); b1.land(); } public void twoButterflies(){ Butterfly b1 = new Butterfly(100, 20); b1.move(5); b1.move(10); b1.move(15); double x = 400*Math.random(); Butterfly b2 = new Butterfly(x, 40); b2.move(10); b1.move(12); b1.move(11); b1.move(7); b1.land(); b2.move(20); b2.move(25); b2.land(); }
135 Objects are values too:Objects can be passed to methods, just like other values. public void Butterflies(){ Butterfly b1 = new Butterfly(100, 20); Butterfly b2 = new Butterfly(x, 40); this.upAndDown(b1); this.upAndDown(b2); } public void upAndDown(Butterfly b){ b.move(10); b.move(15); b.land(); b.move(20);
136 Pattern Make a new object and store in a variable.Call methods on the object stored in the variable. Can have multiple objects of the same type, stored in different variables.
137 Menu More defining methods with parameters Methods that return valuesAdministration:
138 Another Java Program 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 parameters? what actions?
139 ReactionTimeMeasurer/** Measures reaction times for responding to true-false statements */ public class ReactionTimeMeasurer { public ReactionTimeMeasurer(){ UI.addButton("Measure Time", this::measureReactionTime); } /** Measure and report the time taken to react to a question */ public void measureReactionTime() { // 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)
140 ReactionTimeMeasurerReturns a very big integer ⇒ long (milliseconds since 1/1/1970 /** Measure and report the time taken to react to a question */ public void measureReactionTime() { long startTime = System.currentTimeMillis(); UI.askString("Is it true that the sky is blue?"); long endTime = System.currentTimeMillis(); UI.printf("Reaction time = %d milliseconds \n", (endTime - startTime) ); } Just asking one question is not enough for an experiment. need to ask a sequence of questions. only got to here in lecture 6.
141 Multiple questions, the bad way/** Measure and report the time taken to react to a question */ public void measureReactionTime(){ long startTime = System.currentTimeMillis(); UI.askString( "Is it true that John Quay is the Prime Minister"); long endTime = System.currentTimeMillis(); UI.printf("You took %d milliseconds \n", (endTime - startTime) ); startTime = System.currentTimeMillis(); UI.askString( "Is it true that 6 x 4 = 23"); endTime = System.currentTimeMillis(); UI.askString( "Is it true that summer is warmer than winter"); UI.askString( "Is it true that Wellington’s population > 1,000,000"); } Lots of repetition. But not exact repetition. How can we improve it?
142 Good design with methodsKey design principle: Wrap up repeated sections of code into a separate method, Call the method several times: public void measureReactionTime ( ) { this.measureQuestion( ); } public void measureQuestion ( …… ) { long startTime = System.currentTimeMillis(); UI.askString("Is it true that " ……… ); long endTime = System.currentTimeMillis(); UI.printf("You took %d milliseconds \n", (endTime - startTime) ); "John Quay is the Prime Minister"); "6 x 4 = 23"); “Summer is warmer than winter"); "Wellington’s population > 1,000,000 "); We need to parameterise the method String fact fact
143 Improving ReactionTimeMeasurer (1)public void measureReactionTime() { this.measureQuestion("John Quay is the Prime Minister"); this.measureQuestion(“6 x 4 = 23"); this.measureQuestion(“Summer is warmer than Winter"); this.measureQuestion("Wellington’s population > 1,000,000 "); } public void measureQuestion(String fact) { long startTime = System.currentTimeMillis(); UI.askString("Is it true that" + fact); long endTime = System.currentTimeMillis(); UI.printf("You took %d milliseconds \n", (endTime - startTime) );
144 "this" and method calls When you call a method on an object, the method "knows" which object it was called on. stored in the "special variable": this If the method needs to call another method from the same class, it generally needs to call it on the same object. public class MyObjects { : public void method1(){ … this.method2(45, "name"); } public void method2(int num, String n){ But, this. is optional! If you leave the object out of a method call, Java will assume you meant this! To be safe: always put the this. in, until you really know what you are doing.
145 Calling Methods: How does it work?An object is like a filing card in a filing box, marked with its category (class) and an identifier A method definition is like a master copy of a worksheet Every time you call a method on an object, you make a copy of the worksheet, and work through it. The identifier of the object is copied into the box called “this”. Parameters of the method are like boxes at the top of the worksheet: you copy the arguments into the boxes. When you have finished the worksheet, you throw it away, along with any information stored in its boxes.
146 Understanding ReactionTimeMeasurerWhat happens if we call the method on the object RTM1: RTM1 . measureTime(); public void measureReactionTime(){ this.measureQuestion("John Quay is the Prime Minister"); this.measureQuestion("6 x 4 = 23"); this.measureQuestion(“summer is warmer than Winter"); this.measureQuestion("Wellington’s population >1,000,000"); The object the method was called on is copied to "this" place this: RTM- 1
147 Understanding method callspublic void measureQuestion(String fact){ long startTime = System.currentTimeMillis(); UI.askString("Is it true that " + fact); long endTime = System.currentTimeMillis(); UI.printf("You took %d milliseconds \n", (endTime - startTime) ); } "John Quay is…" this: RTM- 1
148 Understanding ReactionTimeMeasurerpublic void measureReactionTime(){ this.measureQuestion("John Quay is the Prime Minister"); this.measureQuestion("6 x 4 = 23"); this.measureQuestion(“summer is warmer than Winter"); this.measureQuestion("Wellington’s population > 1,000,000"); this: RTM-1
149 Understanding ReactionTimeMeasurerNew measureQuestion worksheet: public void measureQuestion(String fact){ long startTime = System.currentTimeMillis(); UI.askString("Is it true that " + fact); long endTime = System.currentTimeMillis(); UI.printf("You took %d milliseconds \n", (endTime - startTime) ); } Each time you call a method, it makes a fresh copy of the worksheet! " 6 x 9 = 54 " this: RTM- 1
150 Understanding ReactionTimeMeasurerpublic void MeasureReactionTime(){ this.measureQn("John Quay is the Prime Minister"); this.measureQn("6 x 4 = 23"); this.measureQn(“summer is warmer than Winter"); this.measureQn(" Wellington’s population > 1,000,000"); this: RTM-1
151 Problem 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: MeasureReactionTime needs to add up the times MeasureQuestion actually measures the time, but prints it out. How do we get the time back from MeasureQuestion to MeasureTime?
152 Methods that return valuesSome methods just have "effects": UI.println("Hello there!"); UI.printf("%4.2f miles is the same as %4.2f km\n", mile, km); UI.fillRect(100, 100, wd, ht); UI.sleep(1000); Some methods just return a value: long now = System.currentTimeMillis(); double distance = 20 * Math.random(); double ans = Math.pow(3.5, 17.3); Some methods do both: double height = UI.askDouble("How tall are you"); Color col =JColorChooser.showDialog(UI.getFrame(), "paintbrush", Color.red);
153 Defining methods to return valuesImproving ReactionTimeMeasurer: public void measureReactionTime() { long time = 0; time = time + this.measureQuestion("John Quay is the Prime Minister"); time = time + this.measureQuestion("11 x 13 = 143"); time = time + this.measureQuestion(“Summer is warmer than Winter"); time = time + this.measureQuestion(" Wellington’s pop > 1,000,000 "); UI.printf("Average reaction time = %d milliseconds\n", (time / 4)); } public void measureQuestion(String fact) { long startTime = System.currentTimeMillis(); …… make measureQuestion return a value instead of just printing it out. . Specifies the type of value returned. void means "no value returned" long
154 Syntax: Method Definitions (v3)/** Measure time taken to answer a question*/ public long measureQuestion ( String fact ){ long startTime = System.currentTimeMillis(); : 〈Comment〉 〈Header〉 〈Body〉 { } public 〈type〉 〈name〉 ( 〈parameters〉 ) 〈type〉 〈name〉 ,
155 Defining methods to return valuesIf you declare that a method returns a value, then the method body must return one! public long measureQuestion(String fact) { long startTime = System.currentTimeMillis(); String ans = UI.askString("Is it true that " + fact); long endTime = System.currentTimeMillis(); UI.printf("You took %d milliseconds\n" , (endTime - startTime) ); } return (endTime - startTime) ; New kind of statement Means: exit the method and return the value The value must be of the right type
156 Returning values. What happens if we call the method:RTM-1 . askQuestions(); public void measureReactionTime(){ long time = 0; time = time + this.measureQuestion("John Quay is the Prime Minister"); time = time + this.measureQuestion("6 x 4 = 23"); time = time + this.measureQuestion(“summer is warmer than Winter"); time = time + this.measureQuestion(“Wellington’s pop > 1,000,000"); this: RTM-1
157 Returning values return value: public long measureQn(String fact){long startTime = System.currentTimeMillis(); UI.askString("Is it true that " + fact); long endTime = System.currentTimeMillis(); return (endTime - startTime) ; } "John Quay is…" this: RTM- 1 " "
158 Returning values. What happens if we call the method:RTM-1 . askQuestions(); public void measureReactionTime(){ long time = 0; time = time + this.measureQuestion("John Quay is the Prime Minister"); time = time + this.measureQuestion("6 x 4 = 23"); time = time + this.measureQuestion(“summer is warmer than Winter"); time = time + this.measureQuestion(" Wellington’s pop > 1,000,000"); this: RTM-1
159 Aside: Random numbers 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) ( Math.random() * 70.0) gives a value between 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
160 Menu Repetition/Iteration Admin: Test SubmissionWhen the assignments are marked, marks and comments are available via the link on the Assignments page
161 loops with bunch of numbers: for plotting and processingneeds arraylist of numbers, and foreach loop. loops with dotoeach loops with a single state varialble while loops for general repetition, eg patterns, nested loops
162 Repetition / IterationDoing some action repeatedly: “Polish each of the cups on the shelf” “Put every chair on top of its desk” “Give a ticket to everyone who passes you” “Keep patrolling around the building until midnight” “Practice the music until you can play it perfectly” Two patterns: Do something to each thing in a collection Do something until some condition changes
163 Repetion/Iteration in Java LDC 4.5Several different ways of specifying repetition. For statement: Do something to each element of a list for ( type value : listOfValues ) { do something to value } While statement: Repeat some action until some condition becomes false while (condition-to-do-it-again ) { actions to perform each time round
164 For statement Three components a list of valuesa variable that is assigned each value of the list in turn. actions to perform for each value in the list // print each number in a list of numbers: for ( Double num : listOfNumbers ) { UI.println(num); } // print each string in a list of numbers that starts with "A": for ( String str : listOfStrings ) { if ( str.startsWith("A") ) { UI.println(str); listOfNumbers: , 32.2, 6.9, 49.5, 83.4, , 1.0 num: listOfStrings: "Jamie", "Andie", "Jules", "Amy", "Mark" str: " "
165 For statement ("foreach" version)for ( Double num : listOfNumbers ) { UI.println(num); } Meaning: Repeatedly (for each value in the list) put the next value of the list into the variable do the actions. for ( type variable : list of values of type ) { action }
166 Lists of values What type is a list of values?How do we get a list of values? ArrayList
167 Lists of values What type is a list of values?How do we get a list of values? ArrayList
168 Doing more with the loops: using VariablesAdd up all the numbers in a list: ArrayList
169 Doing more with the loops: using VariablesCount the number of long names in a list. ArrayList
170 Lists are values too: passing lists aroundpublic void analyseNames() { ArrayList
171 Menu Repetition/Iteration with while Admin: TestMonday 5-6pm: Monday 6-7pm: ABBISS to BROWN KK301 LI to MORTON KK301 BUCK to EVANGELISTA MC101 MULLER to RUSSELL MC101 EVANS to GULLIVER MC102 RYAN to STOECKLEIN MC102 GUNNING to HYDE MC104 STRYDOM to VOGELS MC104 IRVINE to LEUYHOLD CO122 VOSS to VAN'T WOUT CO122
172 While statements: repeating with a conditionFor statements: repetition over a list of values. While statements : general repetition, subject to a condition. while (condition-to-do-it-again ) { actions to perform each time round } while ( true ) { UI.println("this repeats forever!"); int n = 1; while ( n <= 100) { UI.println(n) ; n = n + 1; Similar structure to the if statement
173 While statement Meaning: Similar to if, but NOT THE SAME! RepeatedlyIf the condition is still true, do the actions another time If the condition is false, stop and go on to the next statement. Note: don’t do actions at all if the condition is initially false Similar to if, but NOT THE SAME! keeps repeating the actions, as long as the condition is still true each time round no else — just skips to next statement when condition is false while ( condition ) { action }
174 While with numbers #1 Print a table of numbers and their squares:public void printTable(int max){ int num = 1; while ( num <= max ) { UI.printf(“ %3d %6d %n”, num, (num*num)); num = num + 1; } Repetition with while generally involves initialisation: get ready for the loop test: whether to repeat body: what to repeat “increment”: get ready for the next iteration Initialise Test Body Increment
175 While with numbers #2 Draw a row of squares:public static final double SIZE = 20; ⋮ /** Draws n squares in a horizontal row, starting at (left,top) */ public void drawSquares (int left, int top, int n){ int count = 0; while ( count < n ) { double x = left + count * SIZE; UI.drawRect(x, top, SIZE, SIZE); count = count + 1; } Initialise Test Body Increment ++; Shorthand for count = count + 1
176 While with numbers #3 Counting down: public void countDown(int start){int count = start; while ( count >= 1) { UI.println( count ); count = count – 1; } UI.println(“ GO”); : this.countDown(5);
177 Nested while loops with numbersDraw a grid of circles public void drawCircles(int rows, int cols, int diam ) { int row = 0; while (row < rows) { int col = 0; while ( col < cols ) { int x = LEFT + row*diam; int y = TOP +col*diam; UI.fillOval(x, y, diam, diam); col++; } row++; Outside loop: do each row Inside loop: do each column within the current row
178 Menu More while loops Admin: Test
179 Designing loops with numbersWhen the number of steps is known at the beginning of the loop: int count = 0; int num = 1; while ( count < number) { OR while ( num <= number) { do actions 〉 do actions 〉 count = count + 1; num = num + 1; } } Can count from 0 or from 1 If counting from 0, loop while count is less than target: (count is the number of iterations that have been completed) If counting from 1, loop while num is less than or equal to target: (num is the iteration it is about to do)
180 Designing nested loops with numbers2D structures, eg table of rows and columns: Can do rows in the outside loop and columns in the inside loop, or vice versa int row = 0; int col = 0; while ( row < numberOfRows ) { while ( col < numberOfCols ) { int col = 0; int row = 0; while ( col < numberOfCols ) { while ( row < numberOfRows ) { do actions for row, col 〉 do actions for row, col 〉 col++; row++; } } row++; col++ } }
181 General while loops /** Practice times-tables until got 5 answers correct */ public void playArithmeticGame (){ int score = 0; while ( score < 5) { // ask an arithmetic question int a = this.randomInteger(10); int b = this.randomInteger(10); int ans = UI.askInteger("What is " + a + " times " + b + "?" ); if ( ans == a * b ) { score = score +1; } UI.println("You got 5 right answers" ); public int randomInteger(int max) { return (int) (Math.random() * max ) + 1; }
182 General while loops This seems unnecessarily complex!!/** Ask a multiplication problem until got it right */ public void practiceArithmetic (){ int a = this.randomInteger(10); int b = this.randomInteger(10); String question = "What is " + a + " times " + b + "?"; boolean correct = false; while ( ! correct) { int ans = UI.askInteger(question); if ( ans == a * b ) { correct = true; } UI.println("You got it right!" ); This seems unnecessarily complex!!
183 Loops with the test "in the middle"If the condition for exiting the loop depends on the actions, need to exit in the middle! Common with loops asking for user input. break allows you to exit a loop (while, or for) Must be inside a loop Ignores any if 's Does not exit the method ( return does that ) while ( true ) { actions to set up for the test if ( exit-test ) { break; } additional actions
184 General while loops with break/** Ask a multiplication problem until got it right */ public void practiceArithmetic (){ int a = this.randomInteger(10); int b = this.randomInteger(10); String question = "What is " + a + " times " + b + "?"; boolean correct = false; while ( ! correct) { int ans = UI.askInteger(question); if ( ans == a * b ) { correct = true; } UI.println("You got it right!" ); Only use break when the exit is not at the beginning of the loop. true Setting up for test Test and break break; no additional actions
185 More loops with user inputMake user guess a magic word: public void playGuessingGame(String magicWord){ UI.println("Guess the magic word:"); while (true) { String guess = UI.askString("your guess: "); if ( guess.equalsIgnoreCase(magicWord) ) { UI.println("You guessed it!"); break; } UI.println("No, that wasn't right. Try again!"); Setting up for test Test and break Additional actions
186 Testing your program A) Need to try out your program on sample input while removing the "easy" bugs. Can be a pain if need lots of input (eg TemperatureAnalyser) UI window has a menu item – "set input" – to get input from a text file instead of user typing it. don't have to type lots of data each time Create the text file, eg in Notepad Select file using menu before the program has started asking for input. File can contain multiple sequences of data. B) Need to test your program on a range of inputs Easy, "ordinary", inputs Boundary cases — values that are only just in range, or just out of range Need to check that your if conditions are right Invalid data—does your program handle invalid input correctly? Creating test cases involves creativity – have to try to come up with ways to break your program.
187 Text Input: reading multiple valuesIf there is no input yet, the UI.next…() methods will just wait. ⇒ Always print a prompt to the user before you try to read! It is not safe to call UI.nextInt() or UI.nextDouble() unless you can be certain the next token is an integer / double! How can you tell? UI.hasNextInt() boolean true if next token is an integer UI.hasNextDouble() boolean true if next token is a double UI.hasNext() boolean true if there is a next token (always true for text pane)
188 next vs. nextLine() next(), nextInt(), nextDouble() nextLine()picks up any spaces, discards them, picks up characters to make next “token” (until it reaches a space), returns the token next() returns it as a String nextInt() returns it as an int, nextDouble() returns it as a double. nextLine() Picks up all the characters (including spaces) until it reaches end-of-line character, throws away end-of-line, and returns all the characters (including spaces) as a String.
189 Input with "next" methodsWhat it does Returns next() Read and return next token of user’s input String hasNext() Returns true if there is another token in the user input. Waits for the user to type something if necessary. boolean nextInt() nextDouble() Read the next token of the user's input. Return it as a integer if it is a number. Throws an exception if it is not a number. int double hasNextInt() hasNextDouble() Returns true if next token in the input is an int / double. Waits for user to type something if necessary. nextBoolean() Read the next token of the user's input. Return true if it is "yes", "y", or "true", return false if it is "no", "n", or "false" (case insensitive). Throws an exception if it is anything else. nextLine() Read the remaining characters of the user's input up to (but not including) the next end-of-line and return them as a string. Reads and throws away the end-of-line character. If there are no characters on the line, then it returns an empty string ("").
190 Using next… methods /** sum up all numbers entered by user */ :UI.print(“Enter numbers: end with ‘done’:”); double sum = 0; while (UI.hasNextDouble() ) { //peeking at next value or “token” double amt = UI.nextDouble(); //getting the next value and move pointer sum = sum + amt; } UI.nextLine(); // throw away the ‘done’ UI.printf(“Total of all numbers entered: %.2f %n”, sum); Enter numbers: end with ‘done’: 40 60 30 50 done Total of all numbers entered: * MENU *
191 Menu Files Admin assignments you are important to people!
192 Files The UI text pane window is transient:Typing large amounts of input into the text pane is a pain! It would be nice to be able to save the output of the program easily. Large amounts of text belong in files How can your program read from a file and write to a file? Writing to files is like writing to the UI text pane! Use print, println, printf methods But, need extra objects: File and PrintStream objects Reading from files is a bit different Doesn't use "ask…" methods Need to use "next…" methods And need extra objects: File and Scanner objects
193 Text with the text pane red: 40 green: 60 blue: 30 all doneUI Window red: 40 green: 60 blue: 30 all done UI.askInteger(); UI.println(); My Program : int r =UI.askInteger("red"); int g =UI.askInteger("green"); int b =UI.askInteger("blue"); UI.setColor(new Color(r,g,b); UI.println("all done");
194 Text with Files Needs several objects:Need File object to talk to the actual file on the disk. Need Scanner/PrintStream object to talk to the File object Program talks to the Scanner or PrintStream object. A real file: “myfile.txt” nextInt(); My Program : int r =scan.nextInt(); int g =scan.nextInt(); int b =scan.nextInt(); UI.setColor(new Color(r,g,b); outFile.println("all done"); Scanner object File object PrintStream object println();
195 Using a Scanner Scanner: a class in Java that allows a program to read input from a file (or any other source of characters such as a String, a socket, …) File: a class in Java that connects to an actual file on disk and get characters in and out of the file Program needs to make a File object an get the next token, or the next line String fileName = "My File.txt"; File inFile = new File(fileName); Scanner scan = new Scanner(inFile); ⁞ int r = scan.nextInt(); My File.txt 25 53
196 Scanner A Scanner breaks up the source into a sequence of chunks that the program can get, one at a time. lines, (separated by the end-of-line characters) tokens (separated by spaces, tabs, or end-of-line's) Program can read the next token (or the next line) Scanner scan = new Scanner ( new File("My File.txt") ); while ( scan.hasNext() ){ double radius = scan.nextDouble(); UI.drawOval(X-radius, Y-radius, radius*2, radius*2); } My File.txt 25 53
197 Scanner "next" methods Method What it does Returns next()Read and return next token String nextInt() nextDouble() Read the next token. Return it as a number, if it is a number. Throws an exception if it is not a number. int double nextBoolean() Return true if it is "true"; return false if it is "false". Throws an exception if it is anything else. boolean hasNext() Returns true if there is another token hasNextInt() hasNextDouble() hasNextBoolean() Returns true if there is another token AND the next token is an int / double / Boolean nextLine() Read characters up to the next end-of-line and return them as a string. Reads and throws away the end-of-line character. If the first character is an end-of-line, then it returns an empty string (""). close() close the file
198 Scanner methods. Scanner has a cursor that keeps track of where it is up to in the file. ACCY308 Lecture Tue GBLT2 ACCY308 Lecture Fri GBLT3 ACCY308 Lecture Tue GBLT3 ACCY330 Lecture Fri RHLT2 ACCY330 Lecture Wed RHLT2 ACCY401 Comp-Lab Mon RWW402 ACCY401 Lecture Mon RWW220 ACCY402 Lecture Wed RWW311 ACCY412 Lecture Wed RWW311 ACCY421 Lecture Thu RWW311 ALIN201 Lecture Mon KK204 ALIN201 Lecture Wed KK204 ALIN201 Tutorial Wed AM102 ALIN301 Lecture Tue KK105 ALIN301 Lecture Thu KK105 ALIN301 Tutorial Thu MY103 ANTH101 Lecture Mon KKLT303 ANTH101 Lecture Tue KKLT303
199 Reading lines using Scanner:/** Read lines from a file and print them to UI text pane. */ public void readFile(){ File myfile = new File(“input.txt”); Scanner scan = new Scanner(myfile); UI.println(“ input.txt ”); while (scan.hasNext()){ String line= scan.nextLine(); UI.println(line); } UI.println(“ end of input.txt ”); Almost right, but compiler complains!!! Dealing with files may “raise exceptions” Missing bits to handle exceptions !! 12am up to here
200 Files: handling exceptionsIf a piece of code might raise an exception: Have to enclose it in a try { … } catch (IOException e) { … } public void readFile(){ File myfile = new File(“input.txt”); try { Scanner scan = new Scanner(myfile); while (scan.hasNext()){ String line = scan.nextLine(); UI.println(line); UI.println(“ end of input.txt ”); catch (IOException e) { UI.println(“File failure: ” + e); } what to do what to do if it goes wrong 10am up to here
201 Reading from files: example/** Finds oldest person in file of ages and names. */ public void printOldest(String filename){ try { Scanner scan = new Scanner(new File(filename)); String oldest = ""; int maxAge = 0; while (scan.hasNext()){ int age = scan.nextInt(); String name = scan.nextLine(); if (age > maxAge) { maxAge = age; oldest = name; } UI.printf(“Oldest is %s (%d)%n”, oldest, maxAge); } catch (IOException e) { UI.println("File failure: " + e); } 66 Marie Curie 48 James Clerk Maxwell 84 Isaac Newton 62 Aristotle Read a token, then read rest of line
202 Reading data from a filepublic void drawShapes(String filename){ try { Scanner scan = new Scanner( new File(fileName) ); while ( scan.hasNext() ){ double left = scan.nextDouble(); double top = scan.nextDouble(); String shape = scan.next(); int r = scan.nextInt(); int g = scan.nextInt(); int b = scan.nextInt(); UI.setColor( new Color (r, g, b) ); if (shape.equals("Oval") ){ UI.fillOval(left, top, WIDTH, HEIGHT); } else { UI.fillRect(left, top, WIDTH, HEIGHT); } } catch (IOException e) { UI.println(“File failure: ” + e); } Oval Rect Oval Stop at end of file Reading all the values on the line Do something with all the values
203 A common simple patternFile with one entity per line, described by multiple values: while (sc.hasNext() ){ String type = sc.next(); double cost = sc.nextDouble(); int wheels = sc.nextInt(); String colour = sc.next(); String make = sc.next() if (wheels > 4) { …. } else { … … bicycle green Giant truck black Isuzu car red Toyota Read all the values into variables process the values in the variables
204 Reading files line by lineIf items have a varying number of values: May need to read a line at a time, then process: /**Adds up sales of item on each line of a file */ public void addCounts(){ try { Scanner scan = new Scanner(new File(“data.txt")); while (scan.hasNext()){ String line = scan.nextLine(); Scanner lineSc = new Scanner(line); int code = lineSc.nextInt(); String item = lineSc.next(); int lineTot = 0; while (lineSc.hasNextInt()) { lineTot = lineTot + lineSc.nextInt(); } UI.printf("%s (%d): %d\n", item, code, lineTot); } catch (IOException e) { UI.println("File failure: ” + e); } 973 biscuits 731 cake 3 5 2 189 fruit 446 beans Wrapping a Scanner around a String, Lets you “read” values from the String
205 Files that specify how big they are.Sometimes a data file may specify how many values it contains Can then use a "counted" loop to read the values: try { Scanner scan = new Scanner( new File ( orderFileName ) ); while ( scan.hasNext( ) ){ String model = scan.nextLine(); int count = scan.nextInt(); int totalOrders = 0; int i = 0; while (i < count){ totalOrders = totalOrders + scan.nextInt(); i++; } UI.println( model + " had a total of " + totalOrders + " orders."); scan.close(); } catch (IOException e) { UI.println("File error: " + e); } Honda EV Orders.txt Fit EV 5 35 270 15 380 89 Clarity 6 28 18 9 17 29
206 Files that specify how big they are.Image files: ppm format "Magic number" – code for ppm files read into variables: int cols int rows P3 12 5 255 width (number of columns of pixels) and height (the number of rows of pixels) maximum colour value red-green-blue of each pixel, in turn nested while loops to read colour of each pixel set colour of UI draw pixel.
207 Menu Finishing files Defining Objects Admin Test Assignment …
208 Writing to a File Open a File objectWrap it in a new PrintStream object. Call print, print ln, or printf on it. Close the file try { PrintStream out = new PrintStream(new File("powers-table.txt")); int n=1; out.println("Number\tSquare\tCube"); while ( n <= 1000 ) { out.printf("%4d \t%7d \t%10\n", n, n*n, n*n*n); n = n+1; } out.close() catch (IOException e) { UI.println("File error: " + e); } Just like printing to UI PrintStream Object File Object
209 Checking if files existCan check that file exists before trying to read: public void lineNumber(String fname){ /** Make a copy of a file with line numbers */ File infile = new File(fname); if ( ! infile.exists()) { UI.println("The file " + fname + " doesn't exist"); return; } File outfile = new File("numbered-” +fname); try { Scanner sc = new Scanner ( infile ); PrintStream out = new PrintStream(outfile); int lineNum = 0; while (sc.hasNext()) { out.println(lineNum + ": " + sc.nextLine() ); lineNum++; } out.close(); sc.close(); } catch (IOException e) { UI.printf(“File failure %s\n”, e);}
210 Passing an open scannerFirst method: Just opens and closes the file public void countTokensInFile(String fname){ try { Scanner scan = new Scanner (new File(fname)); int numTokens = this.countTokens(scan); UI.printf(“%s has %d tokens\n”, fname, numTokens); sc.close(); } catch (Exception e) {UI.printf(“File failure %s\n”, e);} } Second Method: Just reads from the scanner and counts public int countTokens (Scanner sc){ int count = 0; while (sc.hasNext()) { sc.next(); // throws result away ! count = count+1; return count; scan: Scanner-2543 File-872 973 biscuits 27 731 cake 3 189 fruit 54 446 beans 1 I sc:
211 UIFileChooser So far, we’ve specified which file to open and read or write with a String. eg: File myfile = new File("input.txt"); How can we allow the user to choose a file? UIFileChooser class (part of ecs100 library, like UI) Method What it does Returns 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; save() User can select file (possibly new) to save to. Returns name of file, or null if the user cancelled. save(String title) Same as save(), but with specified title.
212 Using UIFileChooser methods: open/** allow user to choose and open an existing file*/ String filename = UIFileChooser.open(); File myfile = new File(filename); Scanner scan = new Scanner(myfile); OR Scanner scan = new Scanner(new File(UIFileChooser.open())); /** allow user to choose and open an existing file, specifies a title for dialog box*/ File myfile = new File(UIFileChooser.open(“Choose a file to copy”)); 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.
213 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”));
214 Coercion Mismatching types:double num = scan.nextInt( ); int number = scan.nextDouble( ); Can't do this double squareroot = Math.sqrt(25); but sqrt wants double? String name = “number-” + num; Java will “coerce” a value to the needed type if it can: eg If a method needs a double and is given an int: If an int is assigned to a double variable If “adding” any value to a String But only if it does not lose any information: WON’T coerce a double to an int WON’T coerce a String to a number, or vice versa except when “adding” a number to a String WON’T coerce any object to a mismatching type except when printing or “adding” to a String
215 Casting Where it makes sense to convert a value into another type, but some information may be lost... You can sometimes “cast” the value to the other type: int number = (int) Math.sqrt(49.5); float red = (float) Math.random(); casting a double to an int will lose the fractional part and may mess up the value if the number is too big! Not everything can be cast to everything else! Scanner scan = ( Scanner ) (new File(“data.txt”)); ( 〈new type〉 ) 〈expression〉
216 More about static /** Play a guessing game with the user*/public class GuessingGame{ public static final int maxValue = 40; public void GuessingGame(){ UI.addButton(“Play”, this::playGame); } /** plays rounds of game*/ public void playGame ( ){ … … /** main method */ public static void main(String[ ] args){ new GuessingGame(); static means “Belongs to class as a whole, Not to individual objects” main method - called when the program is run directly from Java - used when running a jar files
217 Static methods: Static methods are methods that don’t need an object:Methods in the Math class are static methods: Math.min(…) Math.max(…) Math.random() Math.sqrt(…) Methods in the UI class are static methods: UI.drawRect(…) UI.println(…) UI.askInt(…) None of these methods need an object to be created first. Methods are called on the class itself, not on an object of that class.
218 Static vs non-static methodsThe 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 ⇒ 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.
219 Classes, Objects, Fields, Constructors COMP 102 #16 & #17 2016
220 Menu Classes and Objects: Chapters 3.1, 5.1-5.5 Admin:defining objects fields: constructors Admin:
221 Why objects? A program has a collection of classesEach class has a collection of methods FlagDrawer class had several methods: public void doJapanFlag () public void doFrenchFlag() Why do you have to create a FlagDrawer object before you can call these methods on it? Why do you have to call the method on an object? What is the object for? ?
222 Classes and Objects A class is a description of a type of object.includes descriptions of methods you can call on this kind of object Some kinds of objects we have used: UI Scanner println… ask… next… next, nextInt, hasNext,… draw… fill… clear… String File length( ), substring… exists… CartoonFigure Flower boilWater, toast, bake … grow, bloom, pick … What else did the objects need? Information/Data, specifying the state of the object. Stored in fields of the object
223 What is an Object An object isA collection of data wrapped up together plus A collection of actions to operate on the collection of data All specified in a class: Fields where data is stored Methods describing the actions Constructor to make new objects Constants Some objects (top level program objects) may have no data.
224 CartoonStory program Java Program with 2D cartoon objectsUses CartoonCharacter objects: Methods: public void lookLeft( ) public void lookRight( ) public void smile( ) public void frown( ) public void walk(double distance) public void speak(String msg) public void think(String msg) Information a CartoonCharacter object must store: its images its size its state (position, direction, emotion)
225 CartoonStory Program public class CartoonStory{public void animate( ){ CartoonCharacter cf1 = new CartoonCharacter(150, 100, “green”); cf1.lookRight; cf1.lookLeft( ); cf1.frown( ) cf1.speak("Is anyone here?"); CartoonCharacter cf2 = new CartoonCharacter(300, 100, “blue”); cf2.smile( ); cf2.lookLeft( ) ; cf2.speak("Hello"); cf1.lookRight( ); cf1.smile( ); cf1.speak("Hi there, I'm Jim"); cf2.speak("I'm Jan"); } Two different objects of the same type Two different objects of the same type
226 Defining a class of objectsCartoonCharacter is not part of the Java libraries ⇒ have to define the class Need to define: methods: specify the actions the objects can do constructor: specifies how to make a new CartoonCharacter object fields: for storing the information about the state of each object
227 CartoonCharacter: methodspublic class CartoonCharacter { public void lookLeft( ) { public void lookRight( ) { // erase figure // erase figure // change direction // change direction // redraw figure // redraw figure } } public void frown( ) { public void smile( ) { // erase figure // erase figure // change emotion // change emotion // redraw figure // redraw figure } } public void walk(double dist) { public void speak(String msg) { // erase figure // draw msg in bubble // change position // wait // redraw figure // erase msg
228 CartoonCharacter: wishful methodspublic class CartoonCharacter { public void lookLeft( ) { public void lookRight( ) { this.erase( ); this.erase( ); // change direction // change direction this.draw( ); this.draw( ); } } public void frown( ) { public void smile( ) { this.erase( ); this.erase( ); // change emotion // change emotion this.draw( ); this.draw( ); } } public void walk(double dist) { public void speak(String msg) { this.erase( ); // draw msg in bubble // change position // wait this.draw( ); // erase msg } } public void erase( ) { public void draw( ) { ??? ???
229 CartoonCharacter: drawpublic void draw( ) { // work out which image to use (eg, “green/right-smile.png”) // draw the image on the graphics pane // wait a bit } String filename = imageFolder+"/"+direction+"-"+emotion+".png" ; UI.drawImage(filename, figX, figY, wd, ht); UI.sleep(500); // wait 500 mS But where are those variables defined? Where do they get their values?
230 Remembering state Each CartoonCharacter object must remember:its state: position emotion direction the folder of image files that it is using. its size Can’t be stored in local variables in a method local variables are “lost” when the method finishes. Have to be stored in the Object itself ⇒ fields values that may change over time
231 Menu Objects and fields Admin Test: Beta-tester opportunity –pickup today, or at school office (3rd floor Cotton) distribution of grades suspected errors in marking? Beta-tester opportunity – startup company working with the School of Design https://tinyurl.com/tryholo get the app free, and
232 CartoonCharacter ObjectsObjects need places to store values – called “Fields” Objects are like entries in your Contacts CartoonCharacter-24 figX: imageFolder: “ ” figY: wd: ht: emotion: “ ” direction: “ ” CartoonCharacter-27 figX: imageFolder: “ ” figY: wd: lecture to here ht: emotion: “ ” direction: “ ”
233 Using fields: A method can refer to a field of the object it was called on: this . fieldname eg: public void lookLeft( ) { this.erase( ) ; this.direction = “left”; this.draw( ) ; } public void draw( ) { String filename = this.imageFolder + ”/” + this.direction + “-” + this.emotion + “.png” ; UI.drawImage(filename, this.figX, this.figY, this.wd, this.ht); UIsleep(500); // wait 500 mS note: fields have no ( ) Object the method was called on
234 Using fields: CartoonCharacter-24 Object figX: wd: figY: ht: 150 40emotion: imageFolder: direction: Object : cf1. lookLeft( ); cf1. walk(20); public void lookLeft( ) { this.erase( ) ; this.direction = “left”; this.draw( ) ; } 150 40 300 80 “smile” “green” “right” “left” cf1: CartoonCharacter-24 ID of Object Method worksheet this: CartoonCharacter-
235 Using fields: CartoonCharacter-24 figX: wd: figY: ht:emotion: imageFolder: direction: Object public void draw( ) { String filename = this. imageFolder + ”/” + this.direction + “-” + this.emotion + “.png” ; UI.drawImage(filename, this.figX, this.figY, this.wd, this.ht); UI.sleep(500); } 150 40 300 80 “smile” “green” “left” Method Worksheet this: CartoonCharacter- “ ”
236 Using fields: CartoonCharacter-24 figX: wd: figY: ht:emotion: imageFolder: direction: Object : cfg1. lookLeft( ); cfg1. walk(20); public void lookLeft( ) { this.erase( ) ; this.direction = “left”; this.draw( ) ; } 150 40 300 80 “smile” “green” “left” cfg1: CartoonCharacter-24 ID of Object this: CartoonCharacter-
237 Using fields: CartoonCharacter-24 figX: wd: figY: ht: 150 40emotion: imageFolder: direction: cfg1.lookLeft( ); cfg1.walk(20); : public void walk (double dist) { this.erase( ) ; if ( this.direction.equals(“right”) { this.figX = this.figX + dist ; } else { this.figX = this.figX – dist ; } this.draw( ) ; } 150 40 300 80 “smile” “green” “left” cfg1: CartoonCharacter-24 this: CartoonCharacter-
238 Objects and Classes Classes define objects:Fields: places in an object that store the information associated with the object methods can refer to fields of the object they were called on: this.fieldname How do you set up the fields? Methods: can be called on any object of the class Constructors: specify how to set up an object when it is first created. Constants: specify names for values
239 Setting up an object Must declare the Fields of an object?Declared in the class (not inside a method) Must specify the type and the name (just like local variables in methods) Can specify an initial value (but you don’t have to!) if not, automatically initialised with 0 or null (unlike local variables) Have a visibility specifier (“private”) Fields remain indefinitely The set of field declarations is a template for the object (just like a method is a template for a worksheet). Just as local variables must be declared
240 Syntax of Field declarations:public class CartoonCharacter { // fields private double figX; // current position of figure private double figY; private String direction = "right"; // current direction it is facing private String emotion = "smiling"; // current emotion private String imageFolder; // base name of images private double wd = 40; // dimensions of figure private double ht=80; // methods ……. private type field name ; = expression Like variables, BUT (a) NOT inside a method (b) have private in front
241 Setting up an object How do you initialise the values in the fields?Can specify an initial value in the field declaration but only if every object should start with the same value!!! Must have a way of setting up different objects when you create them: Constructor: specifies what happens when you make a new object (eg, evaluate the expression new CartoonCharacter(150, 100, “green”) We have seen constructors with no parameters. Can have parameters that can be used to set up the new object.
242 CartoonCharacter classShorthand for declaring two fields (or variables) of the same type public class CartoonCharacter { // fields private double figX, figY; // current position of figure private String direction = "right"; // current direction it is facing private String emotion = "smile"; // current emotion private String imageFolder; // folder where images stored private double wd = 40, ht=80; // dimensions // constructor public CartoonCharacter(double x, double y, String base){ this.imageFolder = base; this.figX = x; this.figY = y; this.draw(); } // methods ……. public void lookLeft() { this.erase(); ….. Got to here in lect 16, 2014T1
243 Syntax of Constructor Definitions (2)public class name ( type parameter name ) { , statement } public CartoonCharacter(String base, double x, double y){ this.imageFolder = base; this.figX = x; this.figY = y; this.draw(); }
244 Constructors Defining a Constructor Constructor typicallyPart of the class Like a method, but called with new Does not have a return type (new always returns an object of the given type) this will hold the new object that is being constructed Constructor typically fills in initial values of fields may call other methods on the object, can do anything an ordinary method can do. The constructor of the “top level” class may set up the user interface.
245 What happens with new ? When an object is created CartoonCharacter-24figX: figY: emotion: direction: imageFolder: wd: ht: When an object is created eg new CartoonCharacter(100, 200 , "yellow"); New chunk of memory is allocated (new filing card). Reference (ID) to object is constructed CartoonCharacter-24 Any initial values specified in the field declarations are assigned to the fields. If no initial value, default values: 0 for fields of a number type (int, double, etc) false for for boolean fields null for fields of an object type (String, Scanner, Car, …) The arguments are passed to the constructor The actions specified in the constructor are performed on the object. The reference is returned as the value of the constructor. 100. 200 “ smile ” “ right ” “ yellow ” null 40. 80.
246 The whole Program Simple class: - no fields - constructor for UI- methods public class CartoonStory{ public CartoonStory(){ UI.addButton(“go”, this::playStory); } public void playStory(){ CartoonCharacter cf1 = new CartoonCharacter(150, 100, “green”); cf1.lookLeft(); cf1.lookRight(); cf1.frown() cf1.speak("Is anyone here?"); CartoonCharacter cf2 = new CartoonCharacter(300, 100, “blue”); cf2.speak("Hello"); cf2.lookLeft() ; cf1.smile(); cf1.speak("Hi there, I'm Jim"); cf2.speak("I'm Jan"); public static void main(String[ ] args){ CartoonStory cs = new CartoonStory(); Note the main method ⇒ don't need BlueJ
247 CartoonCharacter: fields & constructorpublic class CartoonCharacter { // fields private double figX; // current position of figure private double figY; private String direction = "right"; // current direction it is facing private String emotion = "smile"; // current emotion private String imageFolder; // base name of image set private double wd = 40; // dimensions private double ht=80; // constructor public CartoonCharacter(double x, double y, String base){ this.imageFolder = base; this.figX = x; this.figY = y; this.draw(); }
248 CartoonCharacter: methodspublic void lookLeft() { public void lookRight() { this.erase(); this.erase(); this.direction = "left"; this.direction = "right"; this.draw(); this.draw(); } } public void frown() { public void smile() { this.erase(); this.erase(); this.emotion = "frown"; this.emotion = "smile"; this.draw(); this.draw(); } } public void walk(double dist) { this.erase(); if ( this.direction.equals(“right”) { this.figX = this.figX + dist ; } else { this.figX = this.figX – dist ;
249 CartoonCharacter: methodspublic void speak(String msg) { double bubX = this.figX - …; // and bubY, bubWd, bubHt UI.drawOval(bubX, bubY, bubWd, bubHt); UI.drawString(msg, bubX+9, bubY+bubHt/2+3); UI.sleep(500); UI.eraseRect(bubX, bubY, bubWd, bubHt); } public void erase() { UI.eraseRect(this.figX, this.figY, this.wd, this.ht); public void draw() { String filename = this. imageFolder +"/"+this.direction+"-"+ this.emotion+“.png” ; UI.drawImage(filename, this.figX, this.figY, this.wd, this.ht);
250 Running the program: main> java CartoonStory or call main on the class from BlueJ public static void main(String[ ] args){ CartoonStory cs = new CartoonStory(); } cs: CartoonStory-3 CartoonStory-3 Very simple object! - no fields - no constructor
251 CartoonStory Program: playStorypublic void playStory(){ CartoonCharacter cf1 = new CartoonCharacter(150, 100, “green”); cf1.lookLeft(); cf1.lookRight(); cf1.frown() cf1.speak("Is anyone here?"); CartoonCharacter cf2 = new CartoonCharacter(300, 100, “blue”); cf2.speak("Hello"); cf2.lookLeft() ; cf1.smile(); cf1.speak("Hi there, I'm Jim"); cf2.speak("I'm Jan"); this: CartoonStory-3 CartoonCharacter-24 figX: wd: figY: ht: emotion: direction: imageFolder : 150. 100. 40. 80. “ smile ” “ right ” “ green ” cf2: CartoonCharacter- cf1: CartoonCharacter-24 Is anyone here?
252 CartoonStory Program: playStorypublic void playStory(){ CartoonCharacter cf1 = new CartoonCharacter(150, 100, “green”); cf1.lookLeft(); cf1.lookRight(); cf1.frown() cf1.speak("Is anyone here?"); CartoonCharacter cf2 = new CartoonCharacter(300, 100, “blue”); cf2.speak("Hello"); cf2.lookLeft() ; cf1.smile(); cf1.speak("Hi there, I'm Jim"); cf2.speak("I'm Jan"); this: CartoonStory-3 cf1: CartoonCharacter-24 cf2: CartoonCharacter-27 CartoonCharacter-27 figX: wd: figY: ht: emotion: direction: imageFolder : 300. 100. 40. 80. “ smile ” “ right ” “ blue ” Hello
253 Keeping track of Multiple objectsCartoonCharacter-24 figX: wd: figY: ht: emotion: direction: imageFolder : 150. 100. 40. 80. “ frown ” “ right ” “ blue ” CartoonCharacter-27 figX: wd: figY: ht: emotion: direction: imageFolder : 300. 100. 40. 80. “ smile ” “ right ” “ blue ” : cf2.lookLeft() ; cf1.smile(); public void lookLeft() { this.erase() ; this.direction = “left”; this.draw() ; } cf1: CartoonCharacter-24 cf2: CartoonCharacter-27 this: CartoonCharacter-
254 Keeping track of Multiple objectsCartoonCharacter-24 figX: wd: figY: ht: emotion: direction: imageFolder : 150. 100. 40. 80. “ frown ” “ right ” “ blue ” CartoonCharacter-27 figX: wd: figY: ht: emotion: direction: imageFolder : 300. 100. 40. 80. “ smile ” “ left ” “ blue ” : cf2.lookLeft() ; cf1.smile(); public void smile() { this.erase() ; this.emotion = “smile”; this.draw() ; } cf1: CartoonCharacter-24 cf2: CartoonCharacter-27 this: CartoonCharacter-
255 Menu Another example of defining objects Scope, Extent, VisibilityEvent-Driven Input Admin Test marks Beijing Summer School on mobile apps development July 3 -14 Two students will be sent See the forum message Ian Welch if you are interested
256 Bouncing Balls Two classes: Bouncer and BouncingBall
257 Designing Bouncer (“top level” class)How does the user interaction work? buttons, constructor What are the methods?
258 Designing BouncingBall classWhat fields does it need? What methods should it have? What should happen when it is first created?
259 BouncingBall: fields & constructorpublic class BouncingBall { // fields private double xPos; private double height; private double xSpeed; private double ySpeed; private Color col; // constructor public BouncingBall(double x, double y, double sp ){ }
260 BouncingBall: methodspublic void draw () { } public void move() { public double getX() {
261 Places: variables vs fieldsTwo kinds of places to store information: Variables (including parameters) defined inside a method specify places on a worksheet temporary – information is lost when worksheet is finished new place created every time method is called (each worksheet) only accessible from inside the method. Fields defined inside a class, but not inside a method specify places in an object long term – information lasts as long as the object new place created for each object accessible from all methods in the class, and from constructor.
262 Extent and scope A place with a value must be accessible to some code at some time. Extent: how long it will be accessible local variables (and parameters) in methods have a limited extent ⇒ only until the end of the current invocation of the method fields have indefinite extent ⇒ as long as the object exists Scope: what parts of the code can access it Full scope rules are complicated!!! local variables: accessible only to statements inside the block { … } containing the declaration after the declaration fields: at least visible to the containing class; maybe further.
263 Scope of variables //read info from file and display while (scan.hasNext() ){ String ans = scan.next(); if ( ans.equals("flower") ) { Color center = Color.red; int diam = 30; } else if (ans.equals("bud") ) { Color center = Color.green; int diam = 15; : UI.setColor(center); UI.fillOval(x, y, diam, diam); while (scan.hasNext() ){ String ans = scan.next(); Color center = null; int diam = 0; if ( ans.equals("flower") ) { center = Color.red; diam = 15; } else if (ans.equals("bud") ) { center = Color.blue; diam = 30; : UI.setColor(center); UI.fillOval(x, y, diam, diam); ; ; different variables! different variables! Out of scope Out of scope may not be intialised may not be intialised How do you fix it?
264 Fields: scope, visibility, encapsulationFields are accessible to all code in all the (ordinary) methods in the class. Should they be accessible to methods in other classes? ⇒ visibility: public or private public means that methods in other classes can access the fields cfg1.figX = in the CartoonStory class would be OK private means that methods in other classes cannot access the fields cfg1.figX = in the CartoonStory class would be an error. The principle of encapsulation says Keep fields private. Provide methods to access and modify the fields, if necessary ⇒ LDC 5.3
265 Final: fields that don’t varyIf a field will hold a value that should not change (a “constant”): signal it to reader ensure that no code changes it by mistake final is a modifier on field (or variable) declarations means that it can only be assigned to once. public class CartoonFigure { private double figX, figY; private String direction = "right"; private String emotion = "smiling"; private final String ImageFolder; private final double wd = 40 private final double ht = 80; public CartoonCharacter(double x, double y, String folder ){ this.ImageFolder = img // fine – this is the first assignment this.wd = 50; // NO!!! Can't change the previous value
266 public static final: class wide constantsIf a constant has the same value for every object signal that to reader don’t make every object have its own copy static is a modifier on field declarations means that it belongs to the class as a whole, not to each object public class CartoonFigure { private double figX; private double figY; private String direction = "right"; private String emotion = "smiling"; private final String baseImgNm; public static final double WD = 40 public static final double HT=80; CartoonFigure-24 figX: figY: emotion: direction: baseImgNm: . . “ ” “ ” “ ”
267 Menu GUI’s Admin: Buttons Mouse Text Fields and SlidersPuppetMaster program Admin: Test: pick up after lecture today, or at School Office (CO 358),
268 GUI’s and Event driven inputIn a GUI, the interaction is controlled by the user, not by the program User initiates "events" buttons menus mouse press/release/drag text fields sliders keys Program responds
269 PuppetMaster How does Java respond to buttons etc?Smile Frown Right Walk Speak Distance Left How does Java respond to buttons etc? When a button pressed / text entered in box / slider changed / mouse clicked: Java looks up the object & method attached to the button/box/etc Calls the method passing the value for box or slider. passing kind of action and position (x and y) for mouse.
270 Setting up event-driven inputSetting up the GUI: To add a button to the UI: specify name of button and method to call (object ::method or class ::method) (must be a method with no parameters) eg: UI.addButton("go", this::startGame); UI.addButton("end", UI::quit); To add a textfield to the UI: Specify name of textfield and method to call (must be a method with one String parameter) eg UI.addTextField("name", this::setName); To add a slider to the UI: Specify name of slider, min, max, initial values, and method to call (must be a method with one double parameter) eg UI.addSlider("speed", 10, 50, 20, this::setSpeed);
271 Event driven input and fieldsEach event will make a new method call. can't remember anything between events in local variables in the methods. Typically, need fields in the main object to remember information between events. eg: PuppetMaster has to remember the CartoonCharacter object in a field
272 PuppetMaster: Design Structure of the PuppetMaster class:public class PuppetMaster … { // fields to store values between events/method calls private …. // Constructor public PuppetMaster(){ // set up the buttons, slider, textField // initialise fields } // methods to respond to the buttons, slider, textField public void …
273 PuppetMaster: setting up Buttons etcpublic class PuppetMaster … { // fields // constructor public PuppetMaster(){ UI.addButton( "Smile", this::doSmile); UI.addButton( "Frown", this::doFrown); UI.addButton( "Left", this::doLeft); UI.addButton( "Right", this::doRight); UI.addTextField( "Say", this::doSpeak); UI.addButton( "Walk", this::doWalk); UI.addSlider( "Distance", 1, 100, 20, this::setDist); … } // methods to respond Smile Frown Say Left Right Walk Distance 1 100
274 Responding to buttons and textFieldspublic class PuppetMaster { // fields // constructor public PuppetMaster(){ UI.addButton("Smile", this::doSmile); UI.addButton("Frown", this::doFrown); ⋮ UI.addTextField(“Say", this::doSpeak); } public void doSmile(){ // tell the CartoonCharacter to smile public void doFrown(){ // tell the CartoonCharacter to frown public void doSpeak(String words){ // tell the CartoonCharacter to say the words Methods called by buttons must have no parameters A method called by a button must have no parameters Methods called by a textField must have one String parameter
275 PuppetMaster: Using FieldsActions on the CartoonCharacter happen in response to different events ⇒ will be in different method calls ⇒ need to store character in a field, not a local variable. public class PuppetMaster{ // fields private CartoonCharacter cc = new CartoonCharacter(200, 100, "blue"); // constructor public PuppetMaster(){ UI.addButton("Smile", this::doSmile); // call doSmile on this UI.addButton("Frown", this::doFrown); : } public void doSmile(){ this.cc.smile(); public void doFrown(){ this.cc.frown();
276 PuppetMaster: TextFields (boxes)public class PuppetMaster{ private CartoonCharacter cc = new CartoonCharacter(200, 100, "blue"); public PuppetMaster(){ UI.addButton("Smile", this::doSmile); // call doSmile on this UI.addButton("Frown", this::doFrown); UI.addTextField(“Say", this::doSpeak); : } public void doSmile(){ this.cc.smile(); public void doSpeak(String words){ this.cc.speak(words);
277 PuppetMaster: Sliderspublic class PuppetMaster { private CartoonCharacter cc = new CartoonCharacter(200, 100, "blue"); private double walkDist = 20 ; public PuppetMaster(){ UI.addButton("Smile", this::doSmile); : UI.addButton(“Walk", this::doWalk); UI.addSlider( "Distance", 1, 100, 20, this::setDist); } public void doWalk() { this.cc.walk(this.walkDist); public void setDist(double value){ this.walkDist = value; Typical design: field to store value from one event, for use by another event A method called by a slider must have one double parameter
278 GUI: Mouse input Just like buttons, except don’t have to put anything on screen Each press / release / click on the graphics pane will be an event Must tell UI object::method to call when a mouse event occurs UI.setMouseListener(this :: doMouse); Must define method to say how to respond to the mouse parameters: kind of mouse event and position of mouse event public void doMouse(String action, double x, double y) { if (action.equals("pressed") ) { // what to do if mouse button is pressed } else if (action.equals("released") ) { // what to do if mouse button is released else if (action.equals("clicked") ) { // what to do if mouse button is clicked where action occurred press-release in same place
279 Using the mouse. Want to let user specify input with the mouse,eg: drawing lines Typical pattern: On "pressed", just remember the position On "released", do something with remembered position and new position 1 (260,90) (100,80) 2
280 Mouse Input /**Let user draw lines on graphics pane with the mouse. */public class LineDrawer { private double startX, startY; // fields to remember “pressed” position public LineDrawer(){ UI.setLineWidth(10); UI.setMouseListener(this::doMouse); } public void doMouse(String action, double x, double y) { if (action.equals("pressed") ) { this.startX = x; this.startY = y; else if (action.equals("released") ) { UI.drawLine(this.startX, this.startY, x, y);
281 Selecting Colors: JColorChooserpublic class LineDrawer { private double startX, startY; private Color currentColor = Color.black; public LineDrawer (){ UI.setMouseListener(this::doMouse); UI.addButton("Color", this::doChooseColour); } public void doMouse(String action, double x, double y) { if (action.equals("pressed") ) { this.startX = x; this.startY = y; } else if (action.equals("released") ) { UI.drawLine(this.startX, this.startY, x, y); } public void doChooseColour(){ this.currentColor = JColorChooser.showDialog(null, "Choose Color", this.currentColor); UI.setColor(this.currentColor);
282 Menu Designing Classes: the Flower class GUI’s Admin:Responding to key presses Multiple CartoonCharacters A numbers program Admin:
283 Numbers program Program for constructing files of numbers:Allow user to select a new file Allow user to enter a set of numbers with the mouse (height of mouse click is the number) Display numbers as bar chart and list in text pane Save numbers to the file as they are entered User Interface: Button to clear screen and select new file. Graphics pane to select (with mouse) and display the numbers Text pane to display list of numbers Numbers 130 72 281 98 264 97 New
284 Numbers: Design Design: When does something happen? button pressesmouse clicks Fields to store the file (PrintStream) that the numbers are being saved to to remember the horizontal position of the next bar. Constructor set up the interface Methods to respond to mouse record a new number Method to respond to button clear and start a new file Numbers New
285 Numbers: Design public class Numbers { private PrintStream outputFile;private double barX = 0; private static final double BASE= 450; public Numbers(){ UI.setMouseListener(this::doMouse); UI.addButton("New", this::doNew); UI.drawLine(0, BASE, 600, BASE); } public void doNew() {… public void doMouse( … public static void main(String[ ] args){ new Numbers(); Numbers New
286 Respond to Mouse: When user clicks/releases:work out the number they meant draw a bar on the graphics pane display it in the text pane print it to the file public void doMouse(String action, double x, double y) { if (action.equals("released")) { double number = BASE - y; this.barX = this.barX + 10; UI.fillRect(this.barX, y, 5, number); UI.println(number); this.outputFile.println(number); } Numbers 130 What's the problem? New if (this.outputFile != null) { this.outputFile.println(number); }
287 Respond to "New" button public void doNew(){ UI.clearPanes();UI.drawLine(0, BASE, 600, BASE); this.barX = 0; this.outputFile.close(); try{ this.outputFile = new PrintStream(new File(UIFileChooser.save())); } catch(IOException e) { UI.println("File error: "+e); } } // Alternative for the long one line: String fname = UIFileChooser.save(); File file = new File(fname); this.outputFile = new PrintStream(file); if (this.outputFile != null) { this.outputFile.close(); } Still a problem!
288 PuppetMaster: Problem 1Suppose we have two characters! Problem: Which character should smile/turn/walk/speak? Event-driven input can be tricky! Smile Frown Left Right Walk Speak Distance
289 GUI design: choosing object to act onOne typical simple GUI interaction mechanism Select object you want to act on Choose action. Must remember the currently selected object: in a field, because the action will be performed in a later method this.selectedCC = cc1; Typically, the “selected object” doesn’t change until user selects another object.
290 PuppetMaster Problem: two charactersSmile Frown Speak Distance Walk PuppetMaster-3 fields: walkDistance: cc1: CartoonCharacter-11 cc2: CartoonCharacter-12 selectedCC: CartoonCharacter-11 CartoonCharacter-11 emotion: "smile" figX: 110 figY: 200 direction: "right" imgBaseName: "blue" CartoonCharacter-12 emotion: "frown" figX: 350 figY: 200 direction: "left" imgBaseName: "green"
291 PuppetMaster: selecting a character.public class PuppetMaster{ private CartoonCharacter cc1= new CartoonCharacter(“blue", 100, 100); private CartoonCharacter cc2= new CartoonCharacter(“green", 500, 100); private CartoonCharacter selectedCC = cc1; // the selected one private double walkDistance = 20; public PuppetMaster(){ UI.addButton( "Smile", this::doSmile); ⋮ } public void doSmile(){ this.selectedCC.smile(); public void doFrown(){ this.selectedCC.frown(); How do we change the selected character?
292 PuppetMaster: buttons for selectingpublic PuppetMaster() { UI.addButton( "Jim", this::doJim); UI.addButton( "Jan", this::doJan); UI.addButton( "Smile", this::doSmile); ⋮ } public void doJim() { this.selectedCC = this.cc1; public void doJan() { this.selectedCC = this.cc2; public void doSmile(){ this.selectedCC.smile(); public void doWalk() { this.selectedCC.walk(this.walkDistance );
293 PuppetMaster: TextFields & SlidersJim Jan Speak Distance Walk Smile Frown Hello Hello PuppetMaster-3 walkDistance: 20 cc1: CartoonCharacter-11 cc2: CartoonCharacter-12 selectedCC: CartoonCharacter-11 CartoonCharacter-11 emotion: "smile" figX: 110 figY: 200 direction: "right" imgBaseName: "blue" CartoonCharacter-12 emotion: "frown" figX: 350 figY: 200 direction: "left" imgBaseName: "green" 60
294 Shorthand: “Lambda expressions”public class PuppetMaster{ private CartoonCharacter selectedCC = new CartoonCharacter(200, 100, "blue"); public PuppetMaster(){ UI.addButton("Smile", this::doSmile); UI.addButton("Frown", this::doFrown); UI.addTextField(“Say", this::doSpeak); : } public void doSmile(){ this.selectedCC.smile(); public void doFrown(){ this.selectedCC.frown(); public void doSpeak(String words){ this.selectedCC.speak(words); Lots of typing for just one line
295 Shorthand: “Lambda expressions”public class PuppetMaster{ private CartoonCharacter selectedCC = new CartoonCharacter(200, 100, "blue"); public PuppetMaster(){ UI.addButton("Smile", () -> { this.selectedCC.smile(); } ); UI.addButton("Frown", this::doFrown); UI.addTextField(“Say", this::doSpeak); : } public void doSmile(){ this.char.smile(); this.selectedCC.smile(); public void doSpeak(String words){ this.selectedCC.speak(words); Lambda Expression: Unnamed method!! - has parameters - has body - has no name It is a value!!
296 Shorthand: “Lambda expressions”public class PuppetMaster{ private CartoonCharacter selectedCC = new CartoonCharacter(200, 100, "blue"); public PuppetMaster(){ UI.addButton("Smile", () -> { this.selectedCC.smile(); } ); UI.addButton("Frown", () -> { this.selectedCC.frown(); } ); UI.addButton( "Left", () -> { this.selectedCC.lookLeft(); } ); UI.addButton( "Right", () -> { this.selectedCC.lookRight(); } ); UI.addTextField(“Say", (String wds) -> { this.selectedCC.speak(wds); } ); UI.addButton(“Walk", () -> { this.selectedCC.walk(this.walkDist); } ); UI.addSlider( "Distance", 1, 100, 20, (double val) -> { this.walkDist = val; } ); } You do NOT HAVE TO USE THESE!! It is always safe to have an explicit, named method.
297 Shorthand: “Lambda expressions”public class PuppetMaster{ private CartoonCharacter cc1= new CartoonCharacter(“blue", 100, 100); private CartoonCharacter cc2= new CartoonCharacter(“green", 500, 100); private CartoonCharacter selectedCC= cc1; // the selected one private double walkDistance = 20; public PuppetMaster(){ UI.addButton(“Jim", () -> { this.selectedCC = cc1; } ); UI.addButton(“Jan", () -> { this.selectedCC = cc2; } ); UI.addButton("Smile", () -> { this.selectedCC.smile(); } ); UI.addButton("Frown", () -> { this.selectedCC.frown(); } ); UI.addButton( "Left", () -> { this.selectedCC.lookLeft(); } ); UI.addButton( "Right", () -> { this.selectedCC.lookRight(); } ); UI.addTextField(“Say", (String wds) -> { this.selectedCC.speak(wds); } ); UI.addButton(“Walk", () -> { this.selectedCC.walk(this.walkDist); } ); UI.addSlider( "Distance", 1, 100, 20, (double val) -> { this.walkDist = val; } ); }