1 Simple Control Structures booleans, the if statement switch-case
1
Simple Control Structures
booleans, the if statementswitch-case
2
What are control structures? You can’t do very much if your program
consists of just a list of commands to be done in order
– The program cannot choose whether or not to perform a command
– The program cannot perform the same command more than once
– Such programs are extremely limited!
Control structures allow a program to base its behavior on the values of variables
3
boolean boolean is one of the eight primitive types
– booleans are used to make yes/no decisions– All control structures use booleans
There are exactly two boolean values, true (“yes”) and false (“no”)– boolean, true, and false are all lowercase
booleans are named after George Boole, the founder of Boolean logic
4
Declaring boolean variables boolean variables are declared like any other
kind of variable: boolean hungry; boolean passingGrade; boolean taskCompleted = false;
boolean values can be assigned to boolean variables: taskCompleted = true;
5
Numeric comparisons The following numeric comparisons
each give a boolean result: x < y // is x less than y? x <= y// is x less than or equal to y? x == y// is x equal to y? (do not use =) x != y // is x unequal to y? x >= y// is x greater than or equal to y? x > y // is x greater than y?
Reminder: Don’t use == or != for floating-point numbers
6
The if statement The if statement has the form:
if (boolean-expression) statement
Examples: if (passingGrade) System.out.println("Whew!"); if (x > largest) largest = x; if (citBook.price < 40.00) citBook.purchase();
The if statement controls one other statement– Often this isn’t enough; we want to control a group of
statements
7
Compound statements We can use braces to group together several
statements into one “compound” statement: { statement; statement; ...; statement; }
Braces can group any number of statements: { } // OK--this is an “empty” statement { x = 0; } // OK--braces don’t hurt { temp = x;
x = y; y = temp; } //typical use
The compound statement is the only kind of statement that does not end with a semicolon
8
The if statement again The if statement controls one other statement, but it can
be a compound statement Example:
if (cost < amountInPocket) { System.out.println("Spending $" + cost); amountInPocket = amountInPocket - cost;}
It’s good style to use braces even if the if statement controls only a single statement:
if (cost > amountInPocket) { System.out.println("You can't afford it!");}
• I personally make an exception to this style rule when the controlled statement fits easily on the same line with the if:
if (x < 0) x = -x; // use absolute value of x
9
Flowchart for the if statement
condition? statementtrue
false
10
The if-else statement The if-else statement chooses which of two
statements to execute The if-else statement has the form:
if (condition) statement-to-execute-if-true ;else statement-to-execute-if-false ;
Either statement (or both) may be a compound statement
Notice the semicolon after each controlled statement
11
Example if-else statements if (x >= 0) absX = x;
else absX = -x;
if (itemCost <= bankBalance) { writeCheck(itemCost); bankBalance = bankBalance - itemCost;}else { callHome(); askForMoreMoney(2 * itemCost);}
12
Flowchart for the if-else statement
condition?true
statement-1 statement-2
false
13
Aside: the “mod” operator The modulo, or “mod,” operator returns the
remainder of an integer division The symbol for this operation is % Examples:
57 % 10 gives 7 20 % 6 gives 2
Useful rule: x is divisible by y if x % y == 0 If the left operand is negative, the result is
negative (or zero)– Examples: -20 % 3 = -2, 20 % -3 = 2, -20 % -3 = -2
14
Nesting if (or if-then) statements
A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400
if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) leapYear = true; else leapYear = false; } else leapYear = true;}else leapYear = false;
15
Operations on booleans Assume p and q are booleans There are four basic operations on
booleans:– Negation (“not”):
!p is true if p is false (and false otherwise)
– Conjunction (“and”): p && q is true if both p and q are true
– Disjunction (“or”): p || q is true if either of p and q is true
– Exclusive or (“xor”): p ^ q is true if just one of p and q is true
16
Simpler tests A simpler leap-year test:
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) leapYear = true;else leapYear = false;
An even simpler leap-year test:
leapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
17
The if-else statement The if-else statement chooses which of two
statements to execute The if-else statement has the form:
if (condition) statement-to-execute-if-true ;else statement-to-execute-if-false ;
Either statement (or both) may be a compound statement
Notice the semicolon after each statement The else part is optional
18
Dangling Else
Compiler cannot determine which “if” an “else” belongs to if there are no braces
String password = Keyboard.readString();if (password.equals (realPassword)) if (name.equals (“admin”))
loggedIn = superPrivileges = true; else System.out.println (“Error”);
Java matches else with last unfinished if Moral: Use shortcuts at your own risk – or don’t !
19
Multiway selection
Multiple conditions, each of which causes a different block of statements to execute
Can be used where there are more than 2 options
if (condition1){ statements …}else{ if (condition2) { statements … } else …}
20
“if” ladder
Just a nicer way to write multiway selection
if (operation == ‘a’){ answer = first + second;}else if (operation == ‘s’){ answer = first – second;}else if (operation == ‘m’){ answer = first * second;}
21
The “switch” statement
Selects among different statements based on a single integer or character expression
Each set of statements starts in “case” and ends in “break” because switch does not use {}s
– break passes control to statement immediately after switch “default” applies if none of the cases match
22
Sample switch statement
switch (SouperSandwichOrder){ case 1 : cheese = 1; break; case 2 : cheese = 1; tomato = 1; break; case 3 : cheese = 1; tomato = 1; chukka = 1; break; default : cheese = 1; break;}
23
“break” optimisation
If break is omitted, control continues to next statement in the switch
switch (SouperSandwichOrder){ case 3 : chukka = 1; case 2 : tomato = 1; case 1 : default : cheese = 1;}
24
Characters in “switch”
char Operation = Keyboard.readChar (“What to do?”);switch (Operation){ case ‘a’ : answer = a + b; break; case ‘s’ : answer = a – b; break; case ‘m’ : answer = a * b; break; case ‘d’ : if (b != 0) { answer = a / b; break; } default : answer = 0; System.out.println (“Error”); break;}
25
Boolean operators
Boolean Algebra
Java Meaning
AND && true if both parameters are true
OR || true if at least one parameter is true
NOT ! true if parameter is false;false if parameter is true;
26
Operator precedence Now that we have seen how operators can be mixed, we
need precedence rules for all operators– () (highest precedence – performed first)– !– * / %– + -– < <= > >=– == !=– &&– ||– = (lowest precedence – performed last)
27
Reversing expressions
Use ! operator to reverse meaning of boolean expression, e.g.,if (mark >= 0){ // do nothing}else System.out.println (“Error”);
Instead, invert the conditionif (! (mark >= 0)) System.out.println (“Error”);
Can we do better ?
28
Afvinkopdracht 5: Tic-tac-toe
29
Graphic programming
The GUI revisited
30
Java, unlike C & C++, has standard packages for graphics
2 related packages and sub-packages support graphics in Java
– java.awt (Abstract Windows Toolkit)
– javax.swing
AWT is ‘peer-based’– Depends on graphical elements native local platform’s graphics
system
– Unix/Windows graphical programs written using AWT will have a different ‘look and feel’
31
Swing is much more platform independent – Graphical components are pre-built and are simply painted onto
windows
– Relies less on the underlying runtime environment
– Usually slower than AWT-based programs
In practice graphical programs are a mixture of Swing and AWT classes
– AWT takes care of all of the event handling for GUI’s (see later)
32
Frames A frame is a top level window which is a
container for graphical components (canvas, buttons, menus etc)
The AWT has a Frame class and Swing has a JFrame class
The following program displays an empty frame
33
import javax.swing.*;
class MyFrame extends JFrame{
public MyFrame() { setTitle("My first graphics program"); setSize(400,300); }}
public class FrameTest{ public static void main(String[] args) { JFrame frame=new MyFrame(); frame.show(); }}
34
35
A class MyFrame is defined which is a sub-class of JFrame
– A title is added
– The frame is sized to 400x300 (by default, a frame is 0x0)
The frame is created by a call to the constructor
The frame is displayed by a call to JFrame.show()– This creates a separate thread which runs until the program is
terminated – the main thread terminates
36
Swing inheritance hierarchy The JFrame class inherits attributes from
higher level container classes– Typically for resizing and positioning frames
Class names beginning with ‘J’ are Swing classes – everything else is part of AWT
37
Component
Frame
Window
Container
JFrame
JComponent
JPanel…..
38
Most swing components (for example JPanel) are derived from the JComponent class
JFrame, being a top level window, is derived from the Window class
Other top level windows include JApplet and JDialog
39
Displaying graphics in frames – panels
Frames are containers – they can contain other user interface/graphical components
A frame contains a content pane into which components can be added
The following code is typical
Container contentPane=frame.getContentPane();
Component c= ….; // UI or graphical component
contentPane.add (c); // Add to the frame
40
Content pane
FrameJPanel
SomeTextJField
41
Panels Panels (JPanel class) are added to the content pane Panels are themselves containers
– The can contain other UI components– They also have a surface onto which graphics can be drawn
Text Basic shapes (lines, boxes etc) Images
42
Drawing on panels The paintComponent() method in JComponent
(a superclass of JPanel) must be overridden paintComponent() is called automatically when
the window has to be drawn or redrawn – for example when it is moved by the user. It is also called when the repaint() method of a panel is called
43
The following code creates a class MyPanel into which graphics can be drawn
class MyPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
// Code placed here to draw graphics}
}
44
The Graphics object defines the graphics context (fonts, line styles, colours etc)
A call to super.paintComponent() calls the paintComponent() method in JComponent (the base class of JPanel)
– This call sets up the graphics context and performs other complex tasks
45
Displaying text in graphics windows
Text can be drawn onto panels using the Graphics.drawString() method
The text font and size can be optionally set/reset
The following program draws a string onto a panel
– The panel is then added to a frame which is then displayed using JFrame.show()
46
import javax.swing.*;import java.awt.*;
public class MyPanel extends JPanel{
public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("Hello there!",150,125); }}
47
import java.awt.event.*;import javax.swing.*;import java.awt.*;
public class HelloFrame extends JFrame{ public HelloFrame() { setTitle("Drawing a string example"); setSize(400,300); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });
Container contentPane=getContentPane(); contentPane.add(new MyPanel()); }}
48
public class FrameTest{
public static void main(String[] args){
JFrame frame=new HelloFrame(); frame.show();
}}
49
50
Text fonts can be set/reset– The existing font applies until it is reset
The following code sets a bold Helvetica font with a larger font size
public class MyPanel extends JPanel{
public void paintComponent(Graphics g) { super.paintComponent(g);
Font f=new Font(“Helvetica”,Font.BOLD,25); g.setFont(f);
g.drawString("Hello there!",150,125); }}
51
52
Drawing simple graphics Class java.awt.Graphics contains methods which allow
simple graphics to be drawn in different colours Graphics.setcolor() sets the drawing colour
– Colour is represented by the class java.awt.Color(int red, int blue, int green) defining the RGB components
– Preset constants exist (defined as static constants in Color) Color.red Color.orange Color.pink etc
53
Examples of different shapes– Graphics.drawLine(int x1, int y1, int x2, int y2) draws a straight line
from (x1,y1) to (x2,y2)
– Graphics.drawRect(int x, int y, int w, int h) draws a rectangle from upper left hand corner (x,y) with width w and height h
– Graphics.drawOval(int x, int y, int w, int h) draws an outline of an ellipse with a ‘bounding rectangle’ as above
– Graphics.drawPolygon(int[] xc, int[] yc, int n) draws a polygon with n vertices with the co-ordinates being stored in arrays xc and yc
– Graphics.fillOval (int x, int y, int w, int h) fills the oval with the current draw colour
54
class DrawPanel extends JPanel{ public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); g.drawRect(20,30,50,50);
g.setColor(Color.green); g.drawOval(100,30,90,60); g.fillOval(100,30,90,60);
g.setColor(Color.yellow); int[] xcoords={180,200,250,275,225}; int[] ycoords={170,130,130,150,200}; g.drawPolygon(xcoords,ycoords,5); g.fillPolygon(xcoords,ycoords,5); }}
55
56
Displaying images We can read images stored in GIF and JPEG formats and
draw the image onto a graphics panel using Graphics.drawImage()
When an image is read from file, a new thread of execution is started in parallel
– Usually, the program needs to wait until the image is loaded
– Loaded images need to be ‘tracked’ and the program informed when the loading is complete
57
Normal program thread
Load image from fileCreate new thread
Image loading thread
Program waits to be informed when image loaded
Image loading complete – send signal
Normal program thread resumes
58
Image read from file by a Toolkit object– getDefaultToolkit() returns the default toolkit– getDefaultToolkit().getImage(filename) reads the jpg or gif file
containing the image
An image is added to a tracker object which sends a signal back to the panel when the loading is complete
The try/catch statements are for exception handling – causes the program to wait for the image to be loaded (see later)
Following program draws an image into a panel
59
import java.awt.*;import java.awt.event.*;import javax.swing.*;
class ImagePanel extends JPanel{
public ImagePanel(){ image = Toolkit.getDefaultToolkit().getImage(“Pisa.jpg”); MediaTracker tracker=new MediaTracker(this); tracker.addImage(image,0); try {tracker.waitForID(0);} catch (InterruptedException e){}}
public void paintComponent(Graphics g) {
super.paintComponent(g); g.drawImage(image,0,0,this);}
private Image image;}
60
61
And finally …. Swing/AWT are massive and complex
– We have only scratched the surface Typically Java API’s have been built on top of Swing
– Java2D– Java3D
In practice, you would use these to do real work for example involving image processing or 3D rendering
62
“640K ought to be enough for anybody.”
--Bill Gates, 1981
63
Nu inschrijven voor het schaaktoernooi