Top Banner
1 Simple Control Structures booleans, the if statement switch-case
63
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: M C6java5

1

Simple Control Structures

booleans, the if statementswitch-case

Page 2: M C6java5

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

Page 3: M C6java5

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

Page 4: M C6java5

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;

Page 5: M C6java5

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

Page 6: M C6java5

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

Page 7: M C6java5

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

Page 8: M C6java5

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

Page 9: M C6java5

9

Flowchart for the if statement

condition? statementtrue

false

Page 10: M C6java5

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

Page 11: M C6java5

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);}

Page 12: M C6java5

12

Flowchart for the if-else statement

condition?true

statement-1 statement-2

false

Page 13: M C6java5

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

Page 14: M C6java5

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;

Page 15: M C6java5

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

Page 16: M C6java5

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);

Page 17: M C6java5

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

Page 18: M C6java5

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 !

Page 19: M C6java5

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 …}

Page 20: M C6java5

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;}

Page 21: M C6java5

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

Page 22: M C6java5

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;}

Page 23: M C6java5

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;}

Page 24: M C6java5

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;}

Page 25: M C6java5

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;

Page 26: M C6java5

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)

Page 27: M C6java5

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 ?

Page 28: M C6java5

28

Afvinkopdracht 5: Tic-tac-toe

Page 29: M C6java5

29

Graphic programming

The GUI revisited

Page 30: M C6java5

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’

Page 31: M C6java5

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)

Page 32: M C6java5

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

Page 33: M C6java5

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(); }}

Page 34: M C6java5

34

Page 35: M C6java5

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

Page 36: M C6java5

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

Page 37: M C6java5

37

Component

Frame

Window

Container

JFrame

JComponent

JPanel…..

Page 38: M C6java5

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

Page 39: M C6java5

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

Page 40: M C6java5

40

Content pane

FrameJPanel

SomeTextJField

Page 41: M C6java5

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

Page 42: M C6java5

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

Page 43: M C6java5

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}

}

Page 44: M C6java5

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

Page 45: M C6java5

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()

Page 46: M C6java5

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); }}

Page 47: M C6java5

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()); }}

Page 48: M C6java5

48

public class FrameTest{

public static void main(String[] args){

JFrame frame=new HelloFrame(); frame.show();

}}

Page 49: M C6java5

49

Page 50: M C6java5

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); }}

Page 51: M C6java5

51

Page 52: M C6java5

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

Page 53: M C6java5

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

Page 54: M C6java5

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); }}

Page 55: M C6java5

55

Page 56: M C6java5

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

Page 57: M C6java5

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

Page 58: M C6java5

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

Page 59: M C6java5

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;}

Page 60: M C6java5

60

Page 61: M C6java5

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

Page 62: M C6java5

62

“640K ought to be enough for anybody.”

--Bill Gates, 1981

Page 63: M C6java5

63

Nu inschrijven voor het schaaktoernooi