Download presentation
Presentation is loading. Please wait.
Published byStewart Mitchell Modified over 6 years ago
1
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
2
Programs that make decisions
Programs 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);
3
Programs that make decisions
But this just changes the values, not the action itself. To vary the action inside a method: Need a conditional, or choice, statement: IF some condition is true THEN do this action ELSE do that action We do this in English instructions all the time: IF you solved the mouse maze THEN raise your hand IF your name starts with “A” or your name starts with “J” THEN draw a small circle in the top left corner of your notes ELSE draw a small square in the bottom right corner of your notes.
4
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);
5
Java: if and if … else LDC 4.2
Two forms of the if statement: if (〈condition 〉) { 〈actions to perform if condition is true 〉 } ⇒ just skip the actions when the condition is not true ! and if (〈condition 〉 ) { 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.
6
boolean valued expression
if … vs if … else … if ( boolean valued expression ) { statements } else { statements }
7
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?
8
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〉
9
Example with multiway choice
public 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);
10
Example 2 with multi way choice
public 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);
11
Boolean expressions LDC 4.1
What can go in the condition of an if statement? A Boolean value – a value that is either true or false. Boolean expressions: constant values: true, false numeric comparisons: (x > 0) (day <= 7), (x == y), (day != 7) boolean method calls: month.equals("July") word.contains("th") 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”)
12
Writing Boolean expressions
Mostly, boolean expressions are straightforward, There are just a few traps: == is the "equals" operator for simple values, = is assignment (age == 15) vs (age = 15 ); But only use == for numbers (or characters, or references) Use the equals method for Strings, not == (occasionally == will give the right answer by chance!) cur.equals("US") vs cur == "US" String equality is case sensitive: “NZ".equals(“nz") → false “NZ".equalsIgnoreCase(“nz") → true
13
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");
14
Compound Boolean expressions: operators
Using 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 (…)
15
Traps with Boolean expressions
When combining with && and ||, which binds tighter? if ( x > 5 && y <= z || day == 0 ) { …. Use ( and ) whenever you are not sure! if ( ( x > 5 && y <= z ) || day == 0 ) { … if ( x > 5 && ( y <= z || day == 0 ) ) { … The not operator ! goes in front of expressions: if ( !(x > 5 && y <= z ) { … NOT if ( (x !> 5 && y !<= z ) if ( ! cur.equals("US") ) { … NOT if ( cur.!equals("US") ) { … exception: if ( ! (count == 0) ) { … OR if ( count != 0 ) { …
16
Object oriented programming
Key idea of OO programming program structured into classes of objects. each class specifies a kind of object – eg, the actions it can perform. Calling methods in OO languages like java tell an object to perform a method, passing arguments Making objects Some objects are predefined. Create objects with bluej: Right-click on class, and select new …… This is how we run programs with BlueJ. not standard, and not a general solution
17
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)
18
Examples of objects Butterfly program CartoonFigure program
Each butterfly is represented by an object which stores the state of the butterfly (position, wing state, direction) Butterflies have methods move(double dist) and land() 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)
19
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!
20
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
21
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〉 )
22
Reading Documentation
Documentation 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
23
Example: Butterfly Grove program
public 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(); }
24
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);
25
Menu More defining methods with parameters Methods that return values
Administration:
26
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?
27
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)
28
ReactionTimeMeasurer
Returns 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.
29
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?
30
Good design with methods
Key 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
31
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) );
32
Understanding ReactionTimeMeasurer
What 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
33
Understanding method calls
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) ); } "John Quay is…" this: RTM- 1
34
Understanding ReactionTimeMeasurer
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"); this: RTM-1
35
Understanding ReactionTimeMeasurer
New 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
36
Understanding ReactionTimeMeasurer
public 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
37
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?
38
Methods that return values
Some 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);
39
Defining methods to return values
Improving 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
40
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〉 ,
41
Defining methods to return values
If 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
42
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
43
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 " "
44
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
45
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
46
Menu Repetition/Iteration Admin: Test Submission
When the assignments are marked, marks and comments are available via the link on the Assignments page
47
Repetition / Iteration
Doing 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
48
Repetion/Iteration in Java LDC 4.5
Several 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
49
For statement Three components a list of values
a 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: " "
50
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 }
51
Lists of values What type is a list of values?
How do we get a list of values? ArrayList <Double> numberList = UI.askNumbers("Enter numbers"); for (double num : numberList) { UI.println(num); } UI.setColor(Color.red); UI.setLineWidth(5); for (double radius : numberList) { if (radius> 20 && radius < 200) { UI.drawOval( 300 – radius, 250 – radius, radius * 2.0, radius * 2.0); Have to use Double, not double Double is the "wrapped-up" version of double, for putting into a list List of doubles Asks for a list of numbers, ending with 'done'
52
Lists of values What type is a list of values?
How do we get a list of values? ArrayList <String> nameList = UI.askStrings("Enter names"); for (String name : nameList) { UI.println("Hello " + name); } UI.println("=========== Long names ============"); if (name.length() > 6 ) { UI.println(name); } UI.println("=========== Short names ============"); if (name.length() <= 6 ) { UI.print(name + ", "); } UI.println(); List of String values Asks for a list of strings, ending with empty line print without a new line print just a new line
53
Doing more with the loops: using Variables
Add up all the numbers in a list: ArrayList <Double> numberList = UI.askNumbers("Enter numbers"); double total = 0.0; for (double num : numberList) { total = total + num; } UI.println("Total of numbers = " + total ); numberList: , 32.2, 6.9, 49.5, 83.4, , 1.0 Declare and initialise variable Add each number into the total: - Uses current value in total - Adds the next number to it - Puts result back into total
54
Doing more with the loops: using Variables
Count the number of long names in a list. ArrayList <String> nameList = UI.askStrings("Enter names"); int count = 0; for (String name : nameList) { if (name.length() > 6 ) { count = count + 1; } UI.printf("There were %d long names out of %d names \n", count, nameList.size() ); Declare and initialise variable Add 1 to the count Number of values in a list
55
Lists are values too: passing lists around
public void analyseNames() { ArrayList <String> nameList = UI.askStrings("Enter names"); UI.println("Total characters: " + this.totalChars (nameList) ); UI.println("Starts with A: " + this.wordStartingWith(nameList, "A") ); } public int totalChars(ArrayList <String> strings ){ int count = 0; for (String str : strings) { count = count + str.length(); return count; public String wordStartingWith(ArrayList <String> strings, String pattern ){ if ( str.startsWith(pattern) ) { return str; } // returns first word starting with the pattern return "<none>";
56
Menu Repetition/Iteration with while Admin: Test
Monday 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
57
While statements: repeating with a condition
For 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
58
While statement Meaning: Similar to if, but NOT THE SAME! Repeatedly
If 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 }
59
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
60
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
61
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);
62
Nested while loops with numbers
Draw 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
63
Menu More while loops Admin: Test
64
Designing loops with numbers
When 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)
65
Designing nested loops with numbers
2D 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++ } }
66
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; }
67
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!!
68
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
69
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
70
More loops with user input
Make 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
71
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.
72
Menu Files Admin assignments you are important to people!
73
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
74
Text with the text pane red: 40 green: 60 blue: 30 all done
UI 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");
75
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();
76
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
77
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
78
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
79
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
80
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
81
Files: handling exceptions
If 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
82
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
83
Reading data from a file
public 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
84
A common simple pattern
File 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
85
Reading files line by line
If 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
86
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
87
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.
88
Menu Finishing files Defining Objects Admin Test Assignment …
89
Writing to a File Open a File object
Wrap 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
90
Checking if files exist
Can 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);}
91
Passing an open scanner
First 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:
92
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.
93
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.
94
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”));
95
Why objects? A program has a collection of classes
Each 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? ?
96
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
97
What is an Object An object is
A 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.
98
CartoonStory program Java Program with 2D cartoon objects
Uses 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)
99
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
100
Defining a class of objects
CartoonCharacter 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
101
CartoonCharacter: methods
public 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
102
CartoonCharacter: wishful methods
public 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( ) { ??? ???
103
CartoonCharacter: draw
public 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?
104
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 get the app free, and
105
CartoonCharacter Objects
Objects 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: “ ”
106
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
107
Using fields: CartoonCharacter-24 Object figX: wd: figY: ht: 150 40
emotion: 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-
108
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- “ ”
109
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-
110
Using fields: CartoonCharacter-24 figX: wd: figY: ht: 150 40
emotion: 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-
111
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
112
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
113
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
114
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.
115
CartoonCharacter class
Shorthand 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
116
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(); }
117
Constructors Defining a Constructor Constructor typically
Part 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.
118
What happens with new ? When an object is created CartoonCharacter-24
figX: 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.
119
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
120
CartoonCharacter: fields & constructor
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 = "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(); }
121
CartoonCharacter: methods
public 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 ;
122
CartoonCharacter: methods
public 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);
123
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
124
CartoonStory Program: 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"); 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?
125
CartoonStory Program: 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"); 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
126
Keeping track of Multiple objects
CartoonCharacter-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-
127
Keeping track of Multiple objects
CartoonCharacter-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-
128
Menu Another example of defining objects Scope, Extent, Visibility
Event-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
129
Bouncing Balls Two classes: Bouncer and BouncingBall
130
Designing Bouncer (“top level” class)
How does the user interaction work? buttons, constructor What are the methods?
131
Designing BouncingBall class
What fields does it need? What methods should it have? What should happen when it is first created?
132
BouncingBall: fields & constructor
public 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 ){ }
133
BouncingBall: methods
public void draw () { } public void move() { public double getX() {
134
Places: variables vs fields
Two 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.
135
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.
136
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?
137
Fields: scope, visibility, encapsulation
Fields 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
138
GUI’s and Event driven input
In 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
139
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.
140
Setting up event-driven input
Setting 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);
141
Event driven input and fields
Each 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
142
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 …
143
PuppetMaster: setting up Buttons etc
public 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
144
Responding to buttons and textFields
public 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
145
PuppetMaster: Using Fields
Actions 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();
146
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);
147
PuppetMaster: Sliders
public 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
148
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
149
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
150
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);
151
Selecting Colors: JColorChooser
public 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);
152
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
153
Numbers: Design Design: When does something happen? button presses
mouse 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
154
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
155
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); }
156
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!
157
PuppetMaster: Problem 1
Suppose 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
158
GUI design: choosing object to act on
One 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.
159
PuppetMaster Problem: two characters
Smile 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"
160
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?
161
PuppetMaster: buttons for selecting
public 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 );
162
PuppetMaster: TextFields & Sliders
Jim 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
163
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
164
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!!
165
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.
166
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; } ); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.