Java Programming: Guided Learning with Early Objects

Slides:



Advertisements
Similar presentations
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Advertisements

5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Chapter 4: Control Structures I (Selection)
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
Logical Operators and Conditional statements
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Decision Structures and Boolean Logic
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 4: Control Structures I (Selection)
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
TK 1914 : C++ Programming Control Structures I (Selection)
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Chapter 4 Control Structures I. Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Control statements Mostafa Abdallah
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I
Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Boolean Expressions and If
Java Programming: From Problem Analysis to Program Design,
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Making Decisions.
Java Programming: Guided Learning with Early Objects
Control Structures – Selection
Chapter 4: Control Structures I
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Control Structures I (Selection)
Chapter 3: Program Statements
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
Control Structure Chapter 3.
Boolean Expressions to Make Comparisons
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
CprE 185: Intro to Problem Solving (using C)
Control Structure.
Presentation transcript:

Java Programming: Guided Learning with Early Objects Chapter 4 Control Structures I: Selection

Objectives Learn control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Learn how to use the selection control structures if, if…else, and switch in a program Java Programming: Guided Learning with Early Objects

Objectives (continued) Learn how to avoid bugs by avoiding partially understood concepts and techniques Learn about JTextFields and JPanels Java Programming: Guided Learning with Early Objects

Control Structures Four ways a computer processes statements: Sequentially Selection Repetition Method calls Branching: alter execution flow by selection Looping: alter execution flow by repetition Java Programming: Guided Learning with Early Objects

Figure 4-1 Flow of execution examples: (a) sequential, (b) selection, (c) repetition Java Programming: Guided Learning with Early Objects

Relational Operators Express conditions Make comparisons to make decisions Logical (Boolean) expression: has a value of either true or false Relational operator: allows comparisons in a program Relational operators are binary Binary operators require two operands Result of comparison is true or false Java Programming: Guided Learning with Early Objects

Table 4-1 Relational Operators in Java Java Programming: Guided Learning with Early Objects

Relational Operators and Primitive Data Types Relational operators used with integral and floating-point data types Expression Meaning Value 8 < 15 8 less than 15 True 6 != 6 6 not equal to 6 False 2.5 > 5.8 2.5 greater than 5.8 5.9 <= 7.5 5.9 less than or equal to 7.5 true Java Programming: Guided Learning with Early Objects

Comparing Floating-Point Numbers for Equality Check absolute value of difference of two floating-point numbers Difference less than given tolerance Use method abs from class Math Example: Math.abs(x – y) < 0.000001 Java Programming: Guided Learning with Early Objects

Comparing Characters Expression using relational operators evaluates to true or false based on collating sequence Example: ‘R’ > ‘T’ Java Programming: Guided Learning with Early Objects

Table 4-2 Evaluating Expressions Using Relational Operators and the Unicode (ASCII) Collating Sequence Java Programming: Guided Learning with Early Objects

Comparing Strings Strings compared character by character Comparison continues until: Mismatch found Last characters compared and are equal One string exhausted Shorter string less than larger string if comparison equal through shorter string Use method compareTo of class String Java Programming: Guided Learning with Early Objects

Strings, the Assignment Operator, and the Operator new Example 1: String str1 = “Hello”; String str2 = “Hello”; (str1 == str2) evaluates to true str1.equals(str2) evaluates to true Example 2: String str3 = new String(“Hello”); String str4 = new String(“Hello”); (str3 == str4) evaluates to false str3.equals(str4) evaluates to true Java Programming: Guided Learning with Early Objects

Figure 4-3 Variables str1, str2, and the objects they point to Java Programming: Guided Learning with Early Objects

Figure 4-4 Variables str3, str4, and the objects they point to Java Programming: Guided Learning with Early Objects

Wrapper Classes (Revisited) Use method compareTo to compare values of two Integer objects Use method equals to compare values of two Integer objects for equality Relational operators compare values of Integer and Double objects Using autoboxing and auto-unboxing Assignment operator always uses operator new to create Double object Java Programming: Guided Learning with Early Objects

Logical (Boolean) Operators and Logical Expressions Logical (Boolean) operators enable you to combine logical expressions Logical operators take logical values as operands Binary operators: && and || Unary operator: ! Java Programming: Guided Learning with Early Objects

Table 4-6 && (and) Operator Table 4-7 || (or) Operator Java Programming: Guided Learning with Early Objects

Order of Precedence Expression might contain arithmetic, relational, and logical operators Relational and logical operators evaluated left to right Left-to-right associativity Parentheses clarify meaning, override precedence of operators Java Programming: Guided Learning with Early Objects

Table 4-8 Precedence of Operators Java Programming: Guided Learning with Early Objects

Short-Circuit Evaluation Logical expressions evaluated using efficient algorithm Short-circuit evaluation: Logical expression evaluated left to right Stops when value of entire expression known Java Programming: Guided Learning with Early Objects

boolean Data Type and Logical (Boolean) Expressions boolean data type has values true and false Logical expressions manipulated using boolean data type boolean, true, false are reserved words Java Programming: Guided Learning with Early Objects

Selection: if and if…else Logical values permit programs to incorporate decision-making Alters processing flow Three selection or branch control structures: if if…else switch Java Programming: Guided Learning with Early Objects

One-Way Selection One-way selection syntax: if (logical expression) statement logical expression also called condition Determines whether to execute statement If expression true, statement executes statement also called action statement Java Programming: Guided Learning with Early Objects

Figure 4-5 One-way selection Java Programming: Guided Learning with Early Objects

Two-Way Selection May need to choose between two alternatives Java provides if…else statement Two-way selection syntax: if (logical expression) statement1 else statement2 If logical expression is true, statement1 executes Otherwise statement2 executes Java Programming: Guided Learning with Early Objects

Figure 4-7 Two-way selection Java Programming: Guided Learning with Early Objects

Compound (Block of) Statements if and if…else structures select one statement at a time Compound statement (block) permits more complex statements Syntax: { statement1 statement2 … statementn } Java Programming: Guided Learning with Early Objects

Multiple Selections: Nested if Some problems require implementation of more than two alternatives Include multiple selection paths using nested control statements Java associates else with the most recent incomplete if Java Programming: Guided Learning with Early Objects

Comparing if…else Statements with a Series of if Statements a. if (month == 1) System.out.println(“January”); else if (month == 2) System.out.println(“February”); else if (month == 3) System.out.println(“March”); b. if (month == 1) if (month == 2) if (month == 3) Example a executes faster than b Java Programming: Guided Learning with Early Objects

Conditional Operator (? :) (Optional) Conditional operator written as ?: Ternary operator Syntax: expr1 ? expr2 : expr3 Performs an evaluation and returns a value Example: max = (a >= b) ? a : b; Java Programming: Guided Learning with Early Objects

switch Structures switch structure does not require evaluation of logical expression: switch (expr) { case val1: statements1 break; case val2: statements2 default: statements } Java Programming: Guided Learning with Early Objects

Figure 4-8 switch statement Java Programming: Guided Learning with Early Objects

switch Structures (continued) switch statement executes according to value of expression matched against a case label Statements execute until break statement or end of structure If value of expression does not match case labels, default label executes If no default statements, structure skipped break statement causes exit from switch structure If no break statement, execution continues Java Programming: Guided Learning with Early Objects

Choosing Between an if…else and a switch Structure No fixed rules to decide whether to use if…else or switch If multiple selections involve a range of values: Use either if…else or switch structure Convert each range to a distinct value If range of values is large and cannot be reduced: Use if..else structure Java Programming: Guided Learning with Early Objects

Avoiding Bugs by Avoiding Partially Understood Concepts and Techniques Not sufficient to be mostly correct in use of concepts and techniques Many ways to solve a problem Must make correct use of concepts and techniques Do not use a concept or technique until understanding is complete Learn concepts one at a time in a logical order Take time to understand each one Java Programming: Guided Learning with Early Objects

Thermometer Class (Revisited) class Thermometer provides current, maximum, minimum temperature for the day Before method definition, include comments specifying preconditions and postconditions Precondition: statement specifying conditions that must be true before method called Postcondition: statement specifying what is true after method call completed Java Programming: Guided Learning with Early Objects

GUI JTextFields and JPanels (Optional) Display all input and output Text fields: white areas to the right of labels After entering the radius User clicks Calculate button Program calculates and displays the area and circumference User clicks Exit button, program terminates Java Programming: Guided Learning with Early Objects

Figure 4-9 GUI to find and display the circumference and area of a circle Java Programming: Guided Learning with Early Objects

JTextField Text field objects belong to class JTextField Instantiate an object of type JTextField JTextField used for both input and output Complete the design: Create three labels Create two buttons Calculate and Exit Place labels, text fields, buttons in content pane Set title of window, height, width Make window visible Java Programming: Guided Learning with Early Objects

Handling the Events Clicking buttons will generate an event Must write code to handle each event and register listeners class CalculateButtonHandler and class ExitButtonHandler inner classes Inside class CircleProgram Method main instantiates single object of class CircleProgram Java Programming: Guided Learning with Early Objects

Figure 4-10 Sample run for the final CircleProgram Java Programming: Guided Learning with Early Objects

JPanel Sometimes want to vary the number of components in each row Set layout of container to null Specify position of components Use class JPanel JPanel objects are containers Create panels and subpanels Specify layout of each panel Subpanels added to panel below Panels added to content pane Java Programming: Guided Learning with Early Objects

Handling the Events Clicking buttons generates action event One inner class handles all three events public void actionPerformed(ActionEvent e) Parameter e identifies source of event Use method getActionCommand of class ActionEvent Returns command associated with action String str = e.getActionCommand(); Java Programming: Guided Learning with Early Objects

Figure 4-12 Graphical user interface after entering the text Figure 4-13 Graphical user interface after clicking the three buttons Java Programming: Guided Learning with Early Objects

Summary Program statements processed in four ways: Sequentially Selection (branching) Repetition (looping) Method calls Logical expression has value of true or false Also called Boolean expression Relational operator makes comparisons Floating-point numbers compared, given tolerance Java Programming: Guided Learning with Early Objects

Summary (continued) char values compared using collating sequence Strings compared character by character class String provides compareTo method Strings instantiated with assignment statement Strings instantiated with new operator Integers compared for equality using: equals method compareTo Java Programming: Guided Learning with Early Objects

Summary (continued) Assignment operator always uses operator new to create Double object Logical (Boolean) operators allow combining logical expressions Relational and logical operators left-to-right associative Java logical expressions use short-circuit evaluation One-way selection: if Java Programming: Guided Learning with Early Objects

Summary (continued) Two-way selection: if…else Compound statements allow more than one statement to execute in selection structure Selection structures may be nested to allow multiple selection Conditional operator more concise form of if…else statement switch structure does not require evaluation of logical expression Java Programming: Guided Learning with Early Objects

Summary (continued) Learn concepts one at a time in logical order JTextField used for input and output JPanel objects are containers Create a hierarchy of JPanels One handler can handle multiple events Use parameter e of type ActionEvent Use method getActionCommand of class ActionEvent Java Programming: Guided Learning with Early Objects