Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Similar documents
Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 3 Selection Statements

Selections. CSE 114, Computer Science 1 Stony Brook University

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

CONDITIONAL EXECUTION

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

OOP Part 2. Introduction to OOP with Java. Lecture 08: Introduction to OOP with Java - AKF Sep AbuKhleiF -

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

Lecture 1 Java SE Programming

Introduction. Introduction to OOP with Java. Lecture 01: Introduction to OOP with Java - AKF Sep AbuKhleiF -

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Selection Statements. Pseudocode

Eng. Mohammed S. Abdualal

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

In this lab, you will learn more about selection statements. You will get familiar to

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

3chapter C ONTROL S TATEMENTS. Objectives

Chapter 3. Selections

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Python - Week 3. Mohammad Shokoohi-Yekta

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Chapter 4: Control Structures I

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Arithmetic Compound Assignment Operators

Midterm Examination (MTA)

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Introduction to Java Applications

Lecture 3 Tao Wang 1

Repetition, Looping. While Loop

CS1150 Principles of Computer Science Boolean, Selection Statements

Loops. CSE 114, Computer Science 1 Stony Brook University

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Course Outline. Introduction to java

Oct Decision Structures cont d

Elementary Programming

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

IEEE Floating-Point Representation 1

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

++x vs. x++ We will use these notations very often.

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Programming with Java

Conditional Programming

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

CMPT 125: Lecture 4 Conditionals and Loops

Lecture 4. CS118 Term planner. The simple if statement. Control flow: selection. The if... else statement cont... The if... else statement.

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Chapter 2 ELEMENTARY PROGRAMMING

Prof. Navrati Saxena TA: Rochak Sachan

Important Java terminology

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Control Structures in Java if-else and switch

CONDITIONAL EXECUTION: PART 2

JAVA OPERATORS GENERAL

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Computer Components. Software{ User Programs. Operating System. Hardware

Chapter 3: Operators, Expressions and Type Conversion

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

Following is the general form of a typical decision making structure found in most of the programming languages:

CEN 414 Java Programming

Controls Structure for Repetition

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

Java Coding 2. Decisions, decisions!

PROGRAMMING FUNDAMENTALS

Flow of Control. Chapter 3 Part 3 The Switch Statement

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Java Simple Data Types

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

In this chapter, you will:

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

AP COMPUTER SCIENCE A

Lesson 7 Part 2 Flags

( &% class MyClass { }

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

Section 002 Spring CS 170 Exam 1. Name (print): Instructions:

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Zheng-Liang Lu Java Programming 45 / 79

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Introduction to Java & Fundamental Data Types

Conditional Execution

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Chapter 2. Elementary Programming

Transcription:

Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017

Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017

Instructor AbuKhleif, Mohammad Noor Computer Engineer (JU 2012-2017) Software Automation Engineer @ Atypon John Wiley and Sons Company - Jordan Branch Reach me at: moh.noor94@gmail.com facebook.com/moh.noor94 twitter.com/moh_noor94 3

Course Java SE Basics Object Oriented Programming Course Page: /courses/java-101-sep-2017 Or, go to: Courses Java 101 Course Sep 2017 Course Facebook Group: www.facebook.com/groups/akf2017java 4

Let s Start! 5

Quick Review Relational (Comparison) Operators: > >= < <= ==!= Logical Operators: &&! A boolean expression is an expression that evaluates to a boolean value: true or false 6

Selection 7

Motivations If you assigned a negative value for radius in Lecture 02 -Task 2, ComputeVolumeOfCylinder, the program would print an invalid result. If the radius is negative, you don't want the program to compute the volume. How can you deal with this situation? 8

One-way if Statements 9

One-way if Statements A one-way if statement executes an action if an only if the condition is true. If the condition is false, nothing is done. The syntax for a one-way if statement is: if (boolean-expression) { statement(s); } 10

Notes The boolean expression is enclosed in parentheses. if i > 0 { System.out.println("i is positive"); } (a) Wrong if (i > 0) { System.out.println("i is positive"); } (b) Correct The block braces can be omitted if they enclose a single statement. if (i > 0) { System.out.println("i is positive"); } (a) Equivalent if (i > 0) System.out.println("i is positive"); (b) 11

Example Write a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If the number is divisible by 2, print HiEven. 12

Example Solution import java.util.scanner; public class SimpleIfDemo { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter an integer: "); int number = input.nextint(); if (number % 5 == 0) System.out.println("HiFive"); } } if (number % 2 == 0) System.out.println("HiEven"); 13

Let s Code Write a program that prompts the user to enter a string. If the string length is divisible by 2, print EvenString. 14

Two-way if Statements (if else) 15

Two-way if Statements A two-way if-else statement executes an action if the condition is true and another action if the condition is false. The syntax for a two-way if-else statement is: if (boolean-expression) { statement(s); / for the true case } else { statement(s); / for the false case } 16

Two-way if Statements true Statement(s) for the true case Boolean Expression false Statement(s) for the false case 17

Example if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area for the " + "circle of radius " + radius + " is " + area); } else { System.out.println("Negative input"); } 18

Let s Code Write a program that prompts the user to enter his/her name and birth year. If the user is 18 years or older print Welcome [username]. Otherwise, print Sorry, you are not eligible yet, please come back in (18-[userage]) years. 19

Multi-way if Statements (Nested if) 20

Multi-way if Statements An if statement can be inside another if statement to form a nested if statement. Example: if (i > k) { if (j > k) System.out.println( i and j are greater than k ); } else System.out.println( i is less than or equal to k ); 21

Multiple Alternative if Statements - Example score >= 90 true grade = 'A' false score >= 80 true grade = 'B' false score >= 70 rue false score >= 60 false grade = 'C' true grade = 'D' grade = 'F' 22

Multiple Alternative if Statements Example Solution Equivalent, but?! if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Equivalent if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; 23

Let s Code Write a full working program for the previous example, the mark should be entered by the user. 24

Note The else clause matches the most recent if clause in the same block. int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); (a) Equivalent int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); (b) 25

Note, cont. Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); This statement prints B. 26

Common Error Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { area = radius*radius*pi; System.out.println( "The area for the circle of radius " + radius + " is " + area); } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. 27

if (number % 2 == 0) even = true; else even = false; (a) Equivalent boolean even = (number % 2 == 0); (b) Tip 28

if (even == true) System.out.println( "It is even."); (a) Equivalent if (even) System.out.println( "It is even."); (b) Tip 29

switch Statements 30

switch Statements Nested if can be used to write code for multiple conditions. However, it makes the program difficult to read. A switch statement simplifies coding for multiple conditions. A switch statement executes statements based on the value of a variable or an expression. 31

The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1,..., and valuen must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switchexpression. Note that value1,..., and valuen are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x. switch Statements Rules switch (switch-expression) { } case value1: statement(s)1; break; case value2: statement(s)2; break; case valuen: statement(s)n; break; default: statement(s)-for-default; 32

switch Statements Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; case valuen: statement(s)n; break; default: statement(s)-for-default; } 33

switch Statement Rules The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end. 34

Let s Code Problem: Chinese Zodiac Write a program that prompts the user to enter a year and displays the animal for the year. dog rooster monkey sheep pig horse rat snake ox tiger rabbit dragon year % 12 = 0: monkey 1: rooster 2: dog 3: pig 4: rat 5: ox 6: tiger 7: rabbit 8: dragon 9: snake 10: horse 11: sheep 35

Ternary Operator (Conditional Operator) 36

Ternary Operator (Conditional Operator) A conditional operator evaluates an expression based on a condition. The syntax is: booleanexpression? expressioniftrue : expressioniffalse; The result of the conditional operator is expressioniftrue if booleanexpression is true, otherwise the result is expressioniffalse. Example: max = (num1 > num2)? num1 : num2; 37

Let s Code Rewrite the following if-else statement using the ternary operator: if (num % 2 == 0) System.out.println(num + is even ); else System.out.println(num + is odd ); 38

Tasks All tasks should be well-documented, well-designed, and well-styled.

Task 01 (Sort three integers) Write a program that prompts the user to enter three integers and display the integers in non-decreasing order. 40

Task 02 (Find the number of days in a month) Write a program that prompts the user to enter the month and displays the number of days in the month. 41

Task 03 (Financials: currency exchange) Write a program that prompts the user to enter the exchange rate from currency in U.S. dollars to JOD. Prompt the user to enter 0 to convert from U.S. dollars to JOD and 1 to convert from JOD to U.S. dollars. Prompt the user to enter the amount in U.S. dollars or JOD to convert it to JOD or U.S. dollars, respectively. Sample runs in next slide. 42

Task 03 Sample Runs Enter the exchange rate from dollars to JOD: 0.71 Enter 0 to convert dollars to JOD and 1 vice versa: 0 Enter the dollar amount: 100 $100 is 71 JOD Enter the exchange rate from dollars to JOD: 0.71 Enter 0 to convert dollars to JOD and 1 vice versa: 5 Enter the JOD amount: 10000 10000 JOD is $14100 43

Tasks Submission Submit a zipped file contains all the 3.java files, 1 file for each task. Name your zipped file as follow [Lect3_YourName.zip]. Upload your zipped file to the Facebook group. Submission due: Monday, Sep 18-10:00 PM Late submission will not be reviewed by the instructor. Public solutions upload goal is to share knowledge, you can see other s solutions, but, please, don t cheat yourself! Don t forget, all tasks should be well-documented, well-designed, and well-styled. 44

Test Yourself Answer all questions (exclude 3.1 & 3.2): http://www.cs.armstrong.edu/liang/interactivequiz/pu blic_html/chapter3.html 45

References: - Liang, Introduction to Java Programming 10/e - Eng. Asma Abdel Karim Computer Engineering Department, JU Slides. Instructor: AbuKhleif, Mohammad Noor Sep 2017 End of Lecture =D