Presentation is loading. Please wait.

Presentation is loading. Please wait.

GP4, Martin Lillholm 1 Introductory Programming (GP) Spring 2006 Lecture 4 We start at 13:00 Slides are available from the course home page Feel free to.

Similar presentations


Presentation on theme: "GP4, Martin Lillholm 1 Introductory Programming (GP) Spring 2006 Lecture 4 We start at 13:00 Slides are available from the course home page Feel free to."— Presentation transcript:

1 GP4, Martin Lillholm 1 Introductory Programming (GP) Spring 2006 Lecture 4 We start at 13:00 Slides are available from the course home page Feel free to print them now www.itu.dk/courses/GP/F2006 Martin Lillholm

2 GP4, Martin Lillholm 2 Mandatory Assignment How did it go with last week’s mandatory assignment ? –Easy? –Hard? –Many didn’t hand in – why ?

3 GP4, Martin Lillholm 3 Last Week Classes, objects (instances) Attributes (instance variables) Methods and constructors A first look a static methods and variables (class variables) Encapsulation Object/reference variables – variable of non-primitive type The String, Random, Math og Scanner classes Formatted output

4 GP4, Martin Lillholm 4 The Scanner class again Input several (e.g.) integers using one line of input:

5 GP4, Martin Lillholm 5 Formatting Phone Numbers Assignment from last week: L&L Programming Project 3.4 23 00023 DecimalFormat fmt = new DecimalFormat("00000"); System.out.println(fmt.format(23));

6 GP4, Martin Lillholm 6 Java API Specification –Appendix M –http://java.sun.com/j2se/1.5.0/docs/api/index.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/index.html

7 GP4, Martin Lillholm 7 What Have We Skipped so Far? Earlier: –Enumerated types –Wrapper classes and auto boxing –Some GUI Today: –Iterators section 5.6

8 GP4, Martin Lillholm 8 Today More on flow of control Boolean Expressions Relational and logical operators if and switch statements Loop statement –for, do, while Block statements Graphics using loops and conditions – if time allows

9 GP4, Martin Lillholm 9 How Does Today’s Chapter Fit In ? Program execution (normally) begins in the main method. Statements in the main method are executed sequentially – flow of control. Method calls causes flow of control to execute statements in the method (and possible nested method calls) and then return to the next statement in the main method. Conditional statements: Loops statement1 statement2 statement3 statement4 statement5 statement1 statement2 if (condition) statement3 // true statement4 e.g. 10 times Both used in methods bodies incl. main

10 GP4, Martin Lillholm 10 Boolean Expressions Boolean/logical expressions  true or false Has type boolean As opposed to arithmetic expressions  1, 45.78 Has type integer, double,... Boolean expressions are normally formed using relational and logical operators.

11 GP4, Martin Lillholm 11 OperatorMeaningExample <Less than x < 60 <=Less than or equal x <= 60 >Greater than x > 60 >=Greater than or equal x >= 60 ==Equal to x == 60 !=Not equal to x != 60 Relational Operators Argument type typically integer, double, char (primitive types) Resultant type is boolean and has value true or false Has lower precedence than the arithmetic operators, >= has higher precedence than == and !=

12 GP4, Martin Lillholm 12 Boolean Expressions using Relational Operators Examples ( x=2 and y=4 ): ExpressionValue false true true == falsefalse x != ytrue x < 3 + ytrue y < x + 3true (x + y > 3) == falsefalse false != x < 3true x == y == falsetrue

13 GP4, Martin Lillholm 13 Logical Operators OperatorMeaningEksempel ! Not (unary) !(x == 60) && And (binary) 0<= x && x <= 60 || Or (binary) x =60 Both argument and resultant type is boolean ! has higher precedence than && which has higher precedence than || ! has higher precedence than both the relational and arithmetic operators && and || has lower precedence than both the relational and arithmetic operators If expr1 is false in expr1 && expr2 then expr2 isn’t evaluated If expr1 is true in expr1 || expr2 then expr2 isn’t evaluated

14 GP4, Martin Lillholm 14 Logical Operators, Truth Tables x!x truefalse true xyx && yx || y false truefalsetrue false true

15 GP4, Martin Lillholm 15 Examples ( x=2 and y=4 ): Boolean Expressions with Logical Operators UdtrykVærdi !falsetrue !truefalse !true == falsetrue !(true == false)true true && falsefalse false || truetrue (x + y > 3) && x < ytrue x + y == 3 || x < 4true x < y && (3*4 == 2*6-1*2+2) == !(3<x)true

16 GP4, Martin Lillholm 16 The if Statement Used for affecting flow of control based on boolean expressions And is thus used to make choices based on data: –Is one number bigger than another? –Is a number within a certain interval or outside? –Are two String s identical? Is typically used when we need to: –React to data - unknown at compile time –Entered numbers, strings etc. –Data stored in files –Random numbers –... condition S statement(s) true false

17 GP4, Martin Lillholm 17 The if statement – Syntax if ( expr ) statement; if is a reserved word expr has to be boolean and thus evaluate to either true or false If expr evaluates to true, statement is executed and otherwise skipped

18 GP4, Martin Lillholm 18 The if Statement – Examples int a=5; if (a > 10) a = a – 5; System.out.println(”a is: ” + a); if (a>0 && a <=10) System.out.println(”a is in the interval from 1 to 10”); if (a 10) System.out.println(”a isn’t in the interval from 1 to 10”); if (a == 5) a = 3; if (a != 5) a = 5; if (a 10000) System.out.println(”a is negative or very large”);

19 GP4, Martin Lillholm 19 The if Statement – Example Limitations ? Either or... Several statements in the true branch

20 GP4, Martin Lillholm 20 The if-else Statement Syntax if (expr) statement1; else statement2; Examples: if (level > MAX) System.out.println(”Level Critical!”); else System.out.printlnt(”Level ok”); if (a > b -.01 && a < b +.01) a = b; else System.out.println(”a is different from b”); condition statement1 truefalse statement2

21 GP4, Martin Lillholm 21 The if-else – Example

22 GP4, Martin Lillholm 22 if-else – Example

23 GP4, Martin Lillholm 23 Block Statements if (a > b) // swap a and b tmp = a; a = b; b = tmp; else a = a + 1; if (a > b) { // swap a and b tmp = a; a = b; b = tmp; } else a = a + 1; {... } is used to combine statements in blocks as we do in classes, constructor, and methods. A block statement can always substitute any single statement. Indentation doesn’t mean anything – logically speaking – but makes the program a lot more readable

24 GP4, Martin Lillholm 24 Block Statements - Example

25 GP4, Martin Lillholm 25 Nested if Statements – Example

26 GP4, Martin Lillholm 26 Nested if Statements – A Pitfall … if (b < 0) if (a < b) System.out.println(”Både a og b er negative”); else System.out.println(”b er negativ”); if (b < 0) { if (a < b) System.out.println(”Både a og b er negative”); } else System.out.println(”b er negativ”); else always “belongs” to closest unmatched if – bar {} ’s

27 GP4, Martin Lillholm 27 Comparing Data Some primitive types ( integer, long, short, byte ) are compared as we seen so far. Decimal type ( float, double ) are still approximations and always be compared within and certain tolerance and not using e.g == final double TOLERANCE = 0.00001; if (Math.abs(f1-f2) < TOLERANCE) System.out.println(”f1 and f2 are approx. equal”); Characters char is compared using their Unicode: ’0’.. ’9’ < ’A’.. ’Z’ < ’a’... ’ z’ ‘A’ != ‘a’

28 GP4, Martin Lillholm 28 Comparing Data ( String ) Think of strings as a sequence of characters (from left to right). This gives an ordering (lexicographic ordering). “garden” before “gardens” and “Martin” before “anders” Vi cannot use e.g. == and <= directly – see next slide equals and compareTo methods I the String class if (name1.equals(name2)) System.out.println (”The names are the same”); else System.out.println (”The names are not the same”); int result = name1.compareTo(name2); if (result < 0) System.out.println(name1 + ” comes before ” + name2); else if (result == 0) System.out.println (”The name are the same”); else System.out.println (name1 + ” follows ” + name2);

29 GP4, Martin Lillholm 29 Comparing Data (Objects) We’ll return to object comparison in general. But == applied to objects compares references.

30 GP4, Martin Lillholm 30 The switch Statement Alternative construction to select one or more of several statements Based on an integral expression one or more options from a given list is selected – possibly the default option is none matches. Program execution continues a the option that matches the expression option switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: System.out.println(”No match”); }

31 GP4, Martin Lillholm 31 The switch Statement The purpose af break The purpose of default Implicit blocks The expression must be an integral type: ( int, char or (enumerated type)) The cases must be literals Equivalent to a series of if statements but sometimes more elegant

32 GP4, Martin Lillholm 32 switch – Example

33 GP4, Martin Lillholm 33 while Loops Repeats a statement or block 0 or more times while (expr) statement; If expr evaluates to true, statement is executed expr is evaluated again and if true, statement is executed again … Continues until expr evaluates to false int count = 1; while (count <= 5) { Sytem.out.println (count); count++; } Boolean expression statement true false condigtion

34 GP4, Martin Lillholm 34 while loops – Example

35 GP4, Martin Lillholm 35 while loops – Example

36 GP4, Martin Lillholm 36 Infinite Loops int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } while (true) { System.out.println (”This will take a while...”); } int j = 0; while (j < 10) { j = j + 0; System.out.println(j); } double num = 1.0; while (num != 0.0) num = num – 0.1;

37 GP4, Martin Lillholm 37 Nested Loops int count1, count2; count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 50) { System.out.println(”Here again”); count2++; } count1++; }

38 GP4, Martin Lillholm 38 Nested Loops

39 GP4, Martin Lillholm 39 do loops Very similar to while loops except that the condition is evaluated after the body – thus do loops always run at least once do statement; while (expr) int count = 0; do { count++; System.out.println(count); } while (count < 5); true condition statement false Boolean expression

40 GP4, Martin Lillholm 40 do loops – Example

41 GP4, Martin Lillholm 41 for loops for ( initialisation ; condition ; increment ) statement; Initialisation Excuted once before the loop body statement is executed until condition evaluates to false “increment” executed after the loop body at the end of each iteration

42 GP4, Martin Lillholm 42 for loops statement true condition evaluated false increment initialization

43 GP4, Martin Lillholm 43 for loops - Examples int i; for (i=0; i<10; i++) System.out.println(”i:” + i); for (int j=1; j<10; j++) System.out.println(”j:” + j); for (i=9; i >= 0; i--) { k = i + 2; System.out.println(”k:” + k); } –L&L Multiples.java ( side 248 ) –L&L Stars.java ( side 250 )

44 GP4, Martin Lillholm 44 All Loops Constructs are Equivalent while do for

45 GP4, Martin Lillholm 45 Advise on Variable Declaration and Initialisation Declare variables as local as possible Declare variables close to their first use Declare loop variables close to or in the loop construct (only possible for for loops)

46 GP4, Martin Lillholm 46 Graphics using Loops –Bullseye.java og BullseyePanel.java i BlueJ (L&L page 251-254) –Boxes.java (L&L page 255-257)


Download ppt "GP4, Martin Lillholm 1 Introductory Programming (GP) Spring 2006 Lecture 4 We start at 13:00 Slides are available from the course home page Feel free to."

Similar presentations


Ads by Google