Title: Aside simple drawings
1Aside simple drawings
Repeat from last week
- Really just a preview of upcoming topic
- Need a Graphics object to draw on
- Any subclass of JComponent e.g., JPanel can
be passed one by the windowing system - Inherits method paintComponent(Graphics g)
- See DrawPanel.java (Fig. 4.19, p. 142)
- And a window to show it e.g., a JFrame
- See DrawPanelTest (Fig. 4.20, p. 143)
2More iteration structures
- Remember 3 ways to implement loops in Java
- while, for, and do/while
- while loop is most basic
- i.e., can always replace a for loop or do/while
loop with while alone - But other forms are handy, and recommended
sometimes - Exam tip
- Translating a loop is a favorite exam problem
3for Iteration Structure
4for purpose counter-controlled loops
- Recall the 3 steps with while
- int c 0 // initialize control variable
- while (c lt 10) // continuation condition
- System.out.println(cc)
- c c 1 // increment control variable
-
- One for does all
- for (int c0 clt10 c)
- System.out.println(cc)
condition
initialize
increment
5for Notes
- Header requires three fields
- i.e., always two but can leave one or more
blank - Manipulate control variable in the header
- Manipulate other variables in loop body
- Also best to NOT change control variable in body
- Increment not limited to
- Can decrement too for (int i10 igt0 i--)
- Or use any amount for (int i0 ilt100 i5)
- Scope of control variable limited to loop
- Unless it is declared outside the loop
6Applying for loops
- Find the sum of even integers from 2 through 20
- int total 0
- for (int num 2 num lt 20 num 2)
- total num
- Print digits (0 to 9) with spaces between
- for (int i 0 i lt 10 i)
- System.out.print(i )
- // prints 0 1 2 9
- Use to do any operation a fixed number of times
- e.g., Interest.java (Fig. 5.6, p. 167)
7do/while Iteration Structure
8Implementing do/while
- do
- statements
- while (boolean expression)
- Notes
- Always executes at least once
- Good for user input checking
- Dont forget the semicolon at the end
9switch Selection Structure
10Implementing switch
- switch (controlling integral expression)
- case constant integral expression
- statements
- break // important
- case constant integral expression
- statements break
- ...
- default
- statements to do if no case matches
-
- See updated GradeBook.java (Fig 5.9, pp. 171-173)
11switch Notes
- Do NOT forget the breaks!
- Integral types only
- Just byte, short, int, char (but not long)
- And new Java 5 feature enumeration types
- e.g, enum Section FIELD, LOGE, PAVILION
- Constant integral expression (a.k.a., case
label) - No ranges, but can stack, like
- case 1 case 2 case3
- Can always rewrite as nested if statements
- Safer, more structured, recommended in most cases
12break and continue
- Ways to get around the strict structures
- i. e., not really structures anymore
- break completely exits the structure
- continue skips the rest of current iteration
(while, for, or do/while structures only) - Also labeled versions for nested structures
- Usual advice is to find a better way
- i.e., should look for a structured alternative
13Boolean operators , , !
- For combining simple boolean expressions into
more complex expressions - Operands are boolean expressions
- e.g., grade A weight gt 10
- Note relational operators have higher precedence
- Truth tables whole result given partial results
- op1 op2 - true if both operands are true
- op1 op2 - true if either operand is true
- !op - true if operand is false
- See LogicalOperators.java (Fig. 5.18, pp.
184-185) - Note has greater precedence than
14Quiz - Logical Expressions
- Actually just a self-test (but please try anyway)
- Say int x2, y8, z17
- What is (xlty zgtx ygtz)?
- What is (x lt y-z)?
- What is (xy gt y z / y)?
- What is (--z x y)?
- And after that statement executes, what is
- (z gt y x)?
true
false
false
true
false
15How did you do?
Very savvy
Expected after about ½ of CS 5JA
Lagging
Might as well flip a coin!
16More boolean expressions
- Note a difference from math descriptions
- In math (0 lt amount lt 1000)
- In Java (0 lt amount amount lt 1000)
- De Morgans Law has 2 forms, both useful to
simplify boolean expressions - Let A and B represent boolean values
- 1. !(A B) is the same as !A !B
- 2. !(A B) is the same as !A !B
- Q How say not( 0 lt amount lt 1000)?
17Review 7 control structures
18Structure rule 1 start with the simplest
flowchart
- One rectangle
- A good (and widely applicable) example
- get some data, calculate and show some results
- Really just a way to start clarifies the big
picture
19Rule 2 replace any rectangle by two rectangles
in sequence
- This stacking rule can apply repeatedly
one?two, two?three, For example - Get data
- Process
- Show results
20Rule 3 replace any rectangle by any control
structure
- This nesting rule also applies repeatedly, as
each control structure has rectangles - e.g., nest a while loop in an if structure
- if (n gt 0)
- while (i lt n)
- System.out.println(i)
21Rule 4 apply rules 2 and 3 repeatedly, and in
any order
- Stack, nest, stack, nest, nest, stack, gets
more and more detailed as one proceeds - Think of control structures as building blocks
that can be combined in two ways only. - Captures the essence of stepwise refinement keep
adding details as they arise - Basically means keep adding control structures as
long as they are needed - Top-down design start with forest, do trees later
22Programming graphics
- Need a window javax.swing.JFrame
- Several essential steps to use (necessary
plumbing) - Set the size width and height in pixels
- Set a title (optional), and a close operation
- Make it visible
- e.g., see lines 20-25 of ShapesTest (Fig. 5.27,
p. 193) - Add javax.swing.JComponents to window
- Note JPanel is a subclass of JComponent
- Draw shapes, colors, on these components
- Thats all there is to it!
- Except for the painstaking labor, of course
23More?Less?
24Drawing rectangles for example
- Define class that extends JComponent (or one of
its subclasses) - Makes the new class a JComponent subclass too
- Implement paintComponent method
- Use Graphics object passed to this method
- Actually better a Graphics2D object since Java
1.2 - Let that object draw rectangles (or Rectangle
objects) - e.g., Shapes.java (Fig. 5.26, p. 192)
- Or RectangleComponent.java (see links on Slides
page) - Add the component to a frame for viewing
- e.g., ShapesTest or RectangleViewer.java
25Drawing more complex shapes
- A simple car, for example Car.java (see links)
- Acts like a Car that can draw itself
- Car constructor sets x and y locations
- Includes draw(Graphics2D g2) method
- Lets Graphics2D object draw lines, ellipses,
rectangles - A class like CarComponent.java just uses it
- Car myCar new Car(x, y)
- myCar.draw(g2) // passes reference to graphics
object - Still need a window to view it, like
CarViewer.java
26C o l o r
- Current color applies to text, lines, and fills
- g.setColor(Color.RED)
- g.drawLine() // (or g2.draw()) draws in red
- g.setColor(Color.BLUE)
- g.fillRect() // (or g2.fill()) fills with
blue - Custom colors available
- Can set by float values in range 0.0F to 1.0F
- Color gb new Color(0.0F, 0.7F, 1.0F)
- g.setColor(gb)
- Or by int values in range 0 to 255
- g.setColor( new Color(0, 255, 175) )
// also
shows technique if dont need a reference
variable - ColoredSquareComponent.java and ColorViewer.java
27Modularity
- Also a structured programming topic
- Can replace a rectangle with a module
- Modules contain stacked/nested structures
- Java modules
- methods (the most basic modular units)
- classes (collections of related methods)
- packages (collections of related classes)
28Using methods invoking
- Direct translation of algorithm e.g.,
- getData()
- process()
- showResults()
- In turn, the method process() might do
- result calculate(x, y)
- where calculate is another method, one that
returns a value based on x and y. - And so on
29java.lang.Math static methods
- Math is in java.lang so no need to import
- Maths public methods are all static
- So no need to make an object first
- Invoke by class name and the dot . operator
- Math.max(x, y) and Math.min(x, y)
- max and min are overloaded return type same as
x, y - Usually double parameters and return type
- double r Math.toRadians(57.)
- System.out.println(Sine of 57 degrees is
- Math.sin(r))
- Also two constant values Math.PI and Math.E
30Constants
- final variables are constants
- May only assign value once usually when declared
- More efficient code (and often programming)
- Should always avoid magic numbers
- e.g., decipher this line of code
- cost price 1.0775 4.5
- More typing, but worth it
- final double TAX_RATE 0.0775
- final double SHIPPING 4.5
- cost price (1. TAX_RATE) SHIPPING
- Class constants final static variables
- e.g., Math.PI is declared in java.lang.Math as
follows - public static final double PI
3.14159265358979323846
31Some String methods
- Accessing sub-strings (Note positions start
at 0, not 1) - substring(int) returns end of string
- substring(int, int) returns string from first
position to just before last position - charAt(int) returns single char
- length() the number of characters
- toUpperCase(), toLowerCase(), trim(),
- valueOf() converts any type to a String
- But converting from a String more difficult
must use specialized methods to parse
32Note parameters are copies
- e.g., void foo(int x)
- x 5 // changes copy of the value
passed - So what does the following code print?
- int a 1
- foo(a)
- System.out.print(a a)
- Answer a 1
- Same applies to immutable objects like Strings
- String s APPLE
- anyMethod(s)
- System.out.print(s) // prints APPLE
33But references are references
- A reference is used to send messages to an object
- So the original object can change if not
immutable - e.g., void foo(Rectangle x)
- x.translate(5,5)
- // actually moves the rectangle
- Copy of reference is just as useful as the
original - i.e., although methods cannot change a reference,
they can change the original object - Moral be careful about passing object references