Chapter 4: Selection Control Structures

Similar documents
Introduction to Java

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

WRITING DATA TO A BINARY FILE

Sources: On the Web: Slides will be available on:

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Java Crash Course Part I

J a v a Quiz (Unit 3, Test 0 Practice)

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Pemrograman Dasar. Basic Elements Of Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Statements and Control Flow

Computer Programming I

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

AP Computer Science Java Subset

Chapter 2 Introduction to Java programming

Object Oriented Software Design

Object Oriented Software Design

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Example of a Java program

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Introduction to Python

An Incomplete C++ Primer. University of Wyoming MA 5310

Chapter 5. Selection 5-1

Java Basics: Data Types, Variables, and Loops

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Moving from CS 61A Scheme to CS 61B Java

Java Program Coding Standards Programming for Information Technology

Introduction to Object-Oriented Programming

CS 106 Introduction to Computer Science I

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Part I. Multiple Choice Questions (2 points each):

13 File Output and Input

CS 111 Classes I 1. Software Organization View to this point:

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Basic Programming and PC Skills: Basic Programming and PC Skills:

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

The C Programming Language course syllabus associate level

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Topic 11 Scanner object, conditional execution

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Sample CSE8A midterm Multiple Choice (circle one)

Introduction to Java. CS 3: Computer Programming in Java

Course Title: Software Development

Conditional Statements Summer 2010 Margaret Reid-Miller

Programming and Software Development CTAG Alignments

Lecture 2 Notes: Flow of Control

Chapter 2: Elements of Java

Software Engineering Techniques

Variables, Constants, and Data Types

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Computer Programming Tutorial

Selection: Boolean Expressions (2) Precedence chart:

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Java Interview Questions and Answers

Conditions & Boolean Expressions

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

1. Writing Simple Classes:

ECE 122. Engineering Problem Solving with Java

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

COSC282 BIG DATA ANALYTICS FALL 2015 LECTURE 2 - SEP 9

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Introduction to Java Lecture Notes. Ryan Dougherty

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Chapter 1 Java Program Design and Development

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Programmierpraktikum

Spring,2015. Apache Hive BY NATIA MAMAIASHVILI, LASHA AMASHUKELI & ALEKO CHAKHVASHVILI SUPERVAIZOR: PROF. NODAR MOMTSELIDZE

Basic Java Syntax. Program Structure

Lecture 1 Introduction to Java

Building Java Programs

Selection Statements

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Crash Course in Java

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

AP Computer Science Java Mr. Clausen Program 9A, 9B

El Dorado Union High School District Educational Services

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Install Java Development Kit (JDK) 1.8

dictionary find definition word definition book index find relevant pages term list of page numbers

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

The following program is aiming to extract from a simple text file an analysis of the content such as:

Two-way selection. Branching and Looping

Java Programming Fundamentals

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Transcription:

Chapter 4: Selection Control Structures Relational and logical operators. Logical (Boolean) expressions. The selection control structures if, if else, and switch. Java Programming: From Problem Analysis to Program Design, Second Edition 1 Control Structures Three methods of processing a program: In sequence Branching Looping Branch: Altering the flow of program execution by making a selection or choice. Loop: Altering the flow of program execution by repeating statements. Java Programming: From Problem Analysis to Program Design, Second Edition 2 1

Control Structures Java Programming: From Problem Analysis to Program Design, Second Edition 3 Relational Operators Relational operator: Allows you to make comparisons in a program. Binary operator. Condition is represented by a logical expression in Java. Logical expression: An expression that has a value of either true or false. Java Programming: From Problem Analysis to Program Design, Second Edition 4 2

Relational Operators Java Programming: From Problem Analysis to Program Design, Second Edition 5 Relational Operators and Primitive Data Types Can be used with integral and floating-point data types. Can be used with the char data type. Unicode Collating Sequence. Java Programming: From Problem Analysis to Program Design, Second Edition 6 3

Relational Operators and Primitive Data Types Java Programming: From Problem Analysis to Program Design, Second Edition 7 Comparing Strings class String Method compareto Method equals Given string str1 and str2 str1.compareto(str2) = an integer < 0 if string str1< str2 0 if string str1is equaltostringstr2 an integer > 0 if string str1 > str2 Java Programming: From Problem Analysis to Program Design, Second Edition 8 4

Comparing Strings String str1 = "Hello"; String str2 = "Hi"; String str3 = "Air"; String str4 = "Bill"; String str5 = "Bigger"; Java Programming: From Problem Analysis to Program Design, Second Edition 9 Comparing Strings Java Programming: From Problem Analysis to Program Design, Second Edition 10 5

Comparing Strings Java Programming: From Problem Analysis to Program Design, Second Edition 11 Comparing Strings Java Programming: From Problem Analysis to Program Design, Second Edition 12 6

Comparing Strings Java Programming: From Problem Analysis to Program Design, Second Edition 13 Short-Circuit Evaluation A process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known. Java Programming: From Problem Analysis to Program Design, Second Edition 14 7

Selection One-way selection Two-way selection Compound (block of) statements Multiple selections (nested if) Conditional operator switch structures Java Programming: From Problem Analysis to Program Design, Second Edition 15 One-Way Selection Syntax: if (expression) statement Expression referred to as decision maker. Statement referred to as action statement. Java Programming: From Problem Analysis to Program Design, Second Edition 16 8

One-Way Selection Example 4-11 //Determine the absolute value of an integer import javax.swing.joptionpane; public class AbsoluteValue { public static void main(string[] args) { int number; int temp; String numstring; numstring = JOptionPane.showInputDialog ("Enter an integer:"); //Line 1 number = Integer.parseInt(numString); //Line 2 temp = number; //Line 3 Java Programming: From Problem Analysis to Program Design, Second Edition 17 One-Way Selection if (number < 0) //Line 4 number = -number; //Line 5 } JOptionPane.showMessageDialog(null, "The absolute value of " + temp + " is " + number, "Absolute Value", JOptionPane.INFORMATION_MESSAGE); //Line 6 System.exit(0); Java Programming: From Problem Analysis to Program Design, Second Edition 18 9

Two-Way Selection Syntax: if (expression) statement1 else statement2 else statement must be paired with an if. Java Programming: From Problem Analysis to Program Design, Second Edition 19 Two-Way Selection Java Programming: From Problem Analysis to Program Design, Second Edition 20 10

Two-Way Selection Example 4-14 if (hours > 40.0) wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); else wages = hours * rate; Java Programming: From Problem Analysis to Program Design, Second Edition 21 Example 4-15 Two-Way Selection if (hours > 40.0); //Line 1 wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 2 else //Line 3 wages = hours * rate; //Line 4 Because a semicolon follows the closing parenthesis of the if statement (Line 1), the else statement stands alone. The semicolon at the end of the if statement (see Line 1) ends the if statement, so the statement at Line 2 separates the else clause from the if statement. That is, else is by itself. Because there is no separate else statement in Java, this code generates a syntax error. Java Programming: From Problem Analysis to Program Design, Second Edition 22 11

Compound (Block of) Statements Syntax: { statement1 statement2... statementn } Java Programming: From Problem Analysis to Program Design, Second Edition 23 Compound (Block of) Statements if (age > 18) { System.out.println("Eligible to vote."); System.out.println("No longer a minor."); } else { System.out.println("Not eligible to vote."); System.out.println("Still a minor."); } Java Programming: From Problem Analysis to Program Design, Second Edition 24 12

Conditional (? :) Operator Ternary operator Syntax: expression1? expression2 : expression3 If expression1 = true, then the result of the condition is expression2. Otherwise, the result of the condition is expression3. Java Programming: From Problem Analysis to Program Design, Second Edition 25 Multiple Selection: Nested if Syntax: if (expression1) statement1 else if (expression2) statement2 else statement3 Else is associated with the most recent incomplete if. Multiple if statements can be used in place of if else statements. May take longer to evaluate. Java Programming: From Problem Analysis to Program Design, Second Edition 26 13

switch Structures switch (expression) { case value1: statements1 break; case value2: statements2 break;... case valuen: statementsn break; default: statements } Expression is also known as selector. Expression can be an identifier. Value can only be integral. Java Programming: From Problem Analysis to Program Design, Second Edition 27 switch Structures Java Programming: From Problem Analysis to Program Design, Second Edition 28 14

switch Structures Example 4-24 switch (grade) { case 'A': System.out.println("The grade is A."); break; case 'B': System.out.println("The grade is B."); break; case 'C': System.out.println("The grade is C."); break; case 'D': System.out.println("The grade is D."); break; case 'F': System.out.println("The grade is F."); break; default: System.out.println("The grade is invalid."); } Java Programming: From Problem Analysis to Program Design, Second Edition 29 Programming Example: Cable Company Billing Input: Customer s account number, customer code, number of premium channels to which customer subscribes, number of basic service connections (in the case of business customers). Output: Customer s account number and the billing amount. Java Programming: From Problem Analysis to Program Design, Second Edition 30 15

Solution: Programming Example: Cable Company Billing 1. Prompt user for information. 2. Use switch statements based on customer s type. 3. Use an if statement nested within a switch statement to determine the amount due by each customer. Java Programming: From Problem Analysis to Program Design, Second Edition 31 Chapter Summary Control structures are used to process programs. Logical expressions and order of precedence of operators are used in expressions. Compare strings. If statements. if else statements. switch structures. Proper syntax for using control statements. Java Programming: From Problem Analysis to Program Design, Second Edition 32 16