1. Trang chủ
  2. » Thể loại khác

Java - profthinh ď jhtp5_04

40 229 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 40
Dung lượng 350,5 KB

Nội dung

1 Chapter - Control Structures: Part Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while Repetition Statement 4.8 Formulating Algorithms: Case Study (CounterControlled Repetition) 4.9 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study (SentinelControlled Repetition) 4.10 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study (Nested Control Structures) 4.11 Compound Assignment Operators 4.12 Increment and Decrement Operators 4.13 Primitive Types 2003 Prentice Hall, Inc All rights reserved Case Study) Thinking About Objects: 4.14 (Optional 4.1   Introduction • We learn about Control Structures – Structured-programming principle – Control structures help build and manipulate objects (Chapter 8) 2003 Prentice Hall, Inc All rights reserved 4.2 Algorithms • Algorithm – Series of actions in specific order • The actions executed • The order in which actions execute • Program control – Specifying the order in which actions execute • Control structures help specify this order 2003 Prentice Hall, Inc All rights reserved 4.3 Pseudocode • Pseudocode – Informal language for developing algorithms – Not executed on computers – Helps developers “think out” algorithms 2003 Prentice Hall, Inc All rights reserved 4.4 Control Structures • Sequential execution – Program statements execute one after the other • Transfer of control – Three control statements can specify order of statements • Sequence structure • Selection structure • Repetition structure • Activity diagram – Models the workflow • Action-state symbols • Transition arrows 2003 Prentice Hall, Inc All rights reserved add grade to total Corresponding Java statement: total = total + grade; add to counter Corresponding Java statement: counter = counter + 1; Fig 4.1 Sequence structure activity diagram 2003 Prentice Hall, Inc All rights reserved J ava Keywords abstract assert boolean break case catch char class default double else final finally float for implements import instanceof int long native new package protected public return short strictfp super switch synchronized throw throws transient try volatile while Keywords that are reserved, but not currently used const goto Fig 4.2 J ava keywords 2003 Prentice Hall, Inc All rights reserved byte continue extends if interface private static this void 4.4 Control Structures • Java has a sequence structure “built-in” • Java provides three selection structures – if – If…else – switch • Java provides three repetition structures – while – do…while – • Each of these words is a Java keyword 2003 Prentice Hall, Inc All rights reserved 4.5 if Single-Selection Statement • Single-entry/single-exit control structure • Perform action only when condition is true • Action/decision programming model 2003 Prentice Hall, Inc All rights reserved 10 [grade >= 60] print “Passed” [grade < 60] Fig 4.3 if single-selections statement activity diagram 2003 Prentice Hall, Inc All rights reserved 26 Initialize passes to zero Initialize failures to zero Initialize student to one  While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures   Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” Fig 4.10 Pseudocode for examination-results problem 2003 Prentice Hall, Inc All rights reserved 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // Fig 4.11: Analysis.java // Analysis of examination results import javax.swing.JOptionPane; public class Analysis { Outline Loop until student counter is greater than 10 Analysis.java Line 19 public static void main( String args[] ) { // initializing variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int studentCounter = 1; // student counter int result; // one exam result String input; String output; // user-entered Nested value // output string Line 29 control structure // process 10 students using counter-controlled loop while ( studentCounter ) output = output + "\nRaise Tuition"; JOptionPane.showMessageDialog( null, output, "Analysis of Examination Results", JOptionPane.INFORMATION_MESSAGE ); System.exit( ); // terminate application } // end main } // end class Analysis 2003 Prentice Hall, Inc All rights reserved 4.11 Compound Assignment Operators • Assignment Operators – Abbreviate assignment expressions – Any statement of form • variable = variable operator expression; – Can be written as • variable operator= expression; – e.g., addition assignment operator += •c = c + – can be written as • c += 2003 Prentice Hall, Inc All rights reserved 29 30 Assignment Sample Explanation operator expression Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += c = c + -= d -= d = d - *= e *= e = e * /= f /= f = f / %= g %= g = g % Fig 4.12 Arithmetic assignment operators 2003 Prentice Hall, Inc All rights reserved Assigns 10 to c to d 20 to e to f to g 4.12 Increment and Decrement Operators • Unary increment operator (++) – Increment variable’s value by • Unary decrement operator ( ) – Decrement variable’s value by • Preincrement / predecrement operator • Post-increment / post-decrement operator 2003 Prentice Hall, Inc All rights reserved 31 32 Operator C alled ++ preincrement Sample expression ++a Explanation Increment a by 1, then use the new value of a in the expression in which a resides postincrement a++ Use the current value of a in the ++ expression in which a resides, then increment a by predecrement Decrement b by 1, then use the -b new value of b in the expression in which b resides postdecrement b-Use the current value of b in the -expression in which b resides, then decrement b by Fig 4.13 The increment and decrement operators 2003 Prentice Hall, Inc All rights reserved 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig 4.14: Increment.java // Preincrementing and postincrementing operators public class Increment { Outline Line 13 postincrements c public static void main( String args[] ) { int c; // demonstrate postincrement c = 5; // System.out.println( c ); // System.out.println( c++ ); // System.out.println( c ); // System.out.println(); assign to c print Line 21 preincrements print then postincrement print Increment.java Line 13 postincrement c Line 21 preincrement // skip a line // demonstrate preincrement c = 5; // System.out.println( c ); // System.out.println( ++c ); // System.out.println( c ); // assign to c print preincrement then print print } // end main } // end class Increment 5 6  6 3 2003 Prentice Hall, Inc All rights reserved 34 Operators Associativity Type right to left unary postfix ++ -right to left unary ++ + (type) left to right multiplicative * / % left to right additive + left to right relational < >= left to right equality == != right to left conditional ?: right to left assignment = += -= *= /= %= Fig 4.15 Precedenc e and associativity of the operators disc ussed so far 2003 Prentice Hall, Inc All rights reserved 35 4.13 Primitive Types • Primitive types – “building blocks” for more complicated types • Java is strongly typed – All variables in a Java program must have a type • Java primitive types – portable across computer platforms that support Java 2003 Prentice Hall, Inc All rights reserved 36 Type boolean Size in bits char 16 byte short 16 int 32 long 64 float 32 double 64 Fig 4.16The J ava Values true or false Standard [Note: The representation of a boolean is specific to the Java Virtual Machine on each computer platform.] (ISO Unicode character set) '\u0000' to '\uFFFF' (0 to 65535) –128 to +127 (–27 to 27 – 1) –32,768 to +32,767 (–215 to 215 – 1) –2,147,483,648 to +2,147,483,647 (–231 to 231 – 1) –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (–263 to 263 – 1) Negative range: (IEEE 754 floating point) –3.4028234663852886E+38 to –1.40129846432481707e–45 Positive range: 1.40129846432481707e–45 to 3.4028234663852886E+38 Negative range: (IEEE 754 floating point) –1.7976931348623157E+308 to –4.94065645841246544e–324 Positive range: 4.94065645841246544e–324 to 1.7976931348623157E+308 primitive types 2003 Prentice Hall, Inc All rights reserved 4.14 (Optional Case Study) Thinking About Objects: Identifying Class Attributes • Classes have attributes (data) – Implemented in Java programs as variables – Attributes of real-world objects • Radio (object) – Station setting, volume setting, AM or FM (attributes) • Identify attributes – Look for descriptive words and phrases in problem statement – Each identified word and phrase is a candidate attribute • e.g., “the elevator is moving” – “is moving” corresponds to boolean attribute moving • e.g., “the elevator takes five seconds to travel between floors” – corresponds to int attribute travelTime • int travelTime = 5; (in Java) 2003 Prentice Hall, Inc All rights reserved 37 38 C lass ElevatorShaft Descriptive words and phrases [no descriptive words or phrases] Elevator moving summoned current floor destination floor capacity of only one person five seconds to travel between floors unique waiting / moving current floor first or second; capacity for only one person pressed / reset pressed / reset door closed / door open door closed / door open Person Floor FloorButton ElevatorButton FloorDoor ElevatorDoor Bell Light Fig 4.17 [no descriptive words or phrases] turned on / turned off Desc riptive words and phrases from problem statement 2003 Prentice Hall, Inc All rights reserved 4.14 (Optional Case Study) Thinking About Objects: Identifying Class Attributes (Cont.) • UML class diagram – Class attributes are place in the middle compartment – Attributes are written language independently • e.g., attribute open of class ElevatorDoor – open : Boolean = false • May be coded in Java as – boolean open = false; 2003 Prentice Hall, Inc All rights reserved 39 40 ElevatorDoor ElevatorShaft open : Boolean = false Person ID : Integer moving : Boolean = true currentFloor : Integer Floor ElevatorButton pressed : Boolean = false FloorButton pressed : Boolean = false Fig 4.18 Classes with attributes 2003 Prentice Hall, Inc All rights reserved lightOn : Boolean = false Bell floorNumber : Integer capacity : Integer = Elevator moving : Boolean = false summoned : Boolean = false currentFloor : Integer = destinationFloor : Integer = capacity : Integer = travelTime : Integer = Light FloorDoor open : Boolean = false ... Average2 .java // Class-average program with sentinel-controlled repetition import java. text.DecimalFormat; // class to format numbers import javax.swing.JOptionPane; Outline Average2 .java public... do…while – • Each of these words is a Java keyword 2003 Prentice Hall, Inc All rights reserved 9 4.5 if Single-Selection Statement • Single-entry/single-exit control structure • Perform action... static this void 4.4 Control Structures • Java has a sequence structure “built-in” • Java provides three selection structures – if – If…else – switch • Java provides three repetition structures

Ngày đăng: 11/12/2017, 19:43

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w