Eng. Mohammed S. Abdualal

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 3 Selection Statements

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

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

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

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.

ECE 122 Engineering Problem Solving with Java

Methods. Eng. Mohammed Abdualal

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Selection Statements. Pseudocode

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

Lecture 3 Tao Wang 1

Computer System and programming in C

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Declaration and Memory

Chapter 2. Elementary Programming

Selections. CSE 114, Computer Science 1 Stony Brook University

JAVA OPERATORS GENERAL

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

DATA TYPES AND EXPRESSIONS

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

Chapter 2 Elementary Programming

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

CEN 414 Java Programming

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

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Visual C# Instructor s Manual Table of Contents

Zheng-Liang Lu Java Programming 45 / 79

Arithmetic Compound Assignment Operators

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

Values in 2 s Complement

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

COMP Primitive and Class Types. Yi Hong May 14, 2015

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Review for Test 1 (Chapter 1-5)

Chapter 2 ELEMENTARY PROGRAMMING

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

MODULE 02: BASIC COMPUTATION IN JAVA

Elementary Programming

Computer Programming : C++

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

More Programming Constructs -- Introduction

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

Computational Expression

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

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

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

Unit 3. Operators. School of Science and Technology INTRODUCTION

IEEE Floating-Point Representation 1

CS 106 Introduction to Computer Science I

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

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

CONDITIONAL EXECUTION

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Add Subtract Multiply Divide

Reserved Words and Identifiers

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Full file at

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Important Java terminology

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Chapter 2 Primitive Data Types and Operations

Prof. Navrati Saxena TA: Rochak Sachan

Arrays. Eng. Mohammed Abdualal

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Java Primer 1: Types, Classes and Operators

Computational Expression

Introduction to Programming Using Java (98-388)

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

3chapter C ONTROL S TATEMENTS. Objectives

Computer Programming CS F111

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Programming with Java

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Chapter 2: Data and Expressions

CSCI 131, Midterm Exam 1 Review Questions This sheet is intended to help you prepare for the first exam in this course. The following topics have

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Values and Variables 1 / 30

Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 3: Operators, Expressions and Type Conversion

CS111: PROGRAMMING LANGUAGE II

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Course Outline. Introduction to java

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Eng. Mohammed Abdualal

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

Chapter 2: Using Data

AP Computer Science A

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Transcription:

Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 3 Selections Eng. Mohammed S. Abdualal September 25, 2015

Augmented Assignment Operators The operators +, -, *, /, and % can be combined with the assignment operator to form augmented operators. Operator Name Example Equivalent += Addition assignment i += 8 i = i + 8 -= Subtraction assignment i -= 8 i = i - 8 *= Multiplication assignment i *= 8 i = i * 8 /= Division assignment i /= 8 i = i / 8 %= Remainder assignment i %= 8 i = i % 8 Increment and Decrement Operators The increment operator (++) and decrement operator ( ) are for incrementing and decrementing a variable by 1 Task 1: Evaluate The Values of x, y, z, and w WITHOUT Using Java int x = 1; int y = 5; int z = x++ + --y - ++x; int w = x-- + ++y - z-- * x++ - ++y / 6; 2

Numeric Type Conversions You can always assign a value to a numeric variable whose type supports a larger range of values. You cannot, however, assign a value to a variable of a type with a smaller range unless you use type casting. Casting is an operation that converts a value of one data type into a value of another data type. Casting a type with a small range to a type with a larger range is known as widening a type. Casting a type with a large range to a type with a smaller range is known as narrowing a type. Java will automatically widen a type, but you must narrow a type explicitly. Data types ranges in java are increase as following: byte < short < int < long < float < double Widening int i = 10; double d = i; // Widening since double s range is greater than int s range // d = 10.0 Note: when a double or a float value is cast into an int value, the fractional part is truncated. float f = 10.2f; int i = (int)f; // i = 10 Narrowing 3

boolean Data Type The boolean data type declares a variable with the value either true or false. boolean b = true; Example These values (true, false) are literals, just like numbers such as 10. They are treated as reserved words and cannot be used as identifiers in the program. Note that the result of any comparison operation will be a boolean value. Example double radius = 5; System.out.println(radius > 0); // this program will prints true on the console since 5 is greater than 0 The previous example uses greater than comparison operator. Java provides five more comparison operators, shown in the following table (assume radius is 5 in the table). 4

if Statements An if statement is a construct that enables a program to specify alternative paths of execution. If the boolean-expression evaluates to true, the statements in the block are executed. Example: calculating the area of a circle only if its radius is greater than 0. Using if Statement String s = JOptionPane.showInputDialog("Enter a radius"); double radius = Double.parseDouble(s); double area; if (radius >= 0) { area = radius * radius * 3.14; System.out.println("The area for the circle of radius " + radius + " is " + area); } Note: you can omit the braces if the block contains a single statement. 5

Two-Way if-else Statements An if-else statement decides the execution path based on whether the condition is true or false. if-else statement contains two blocks. The first one is if-block and will be executed when the condition is true. The second is else-block and will be executed when the condition is false. Example: Using if-else Statements String s = JOptionPane.showInputDialog("Enter a radius"); double radius = Double.parseDouble(s); double area; if (radius >= 0) { area = radius * radius * 3.14; System.out.println("The area for the circle of radius " + radius + " is " + area); } else { System.out.println("Error! Radius cannot be negative!"); } Nested if and Multi-Way if-else Statements An if statement can be inside another if statement to form a nested if statement. The nested if statement can be used to 6

implement multiple alternatives. The following example prints a letter grade according to the score, with multiple alternatives: Using Multi-Way if-else Statements String s = JOptionPane.showInputDialog("Enter your grade"); int grade = Integer.parseInt(s); if (grade >= 90) { System.out.println("A"); } else if (grade >= 80) { System.out.println("B"); } else if (grade >= 70) { System.out.println("C"); } else if (grade >= 60) { System.out.println("D"); } else { System.out.println("F"); } Logical Operators Sometimes, whether a statement is executed is determined by a combination of several conditions. You can use logical operators to combine these conditions to form a compound Boolean expression. Logical operators, also known as Boolean operators, operate on Boolean values to create a new Boolean value. The following table lists four logical operators provided by Java: Task 2 Modify the previous example to ensure that the grade is between 0 and 100. If not, then output error message to the user. 7

Example: Determining Leap Year. A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400. You can use the following Boolean expressions to check whether a year is a leap year: // A leap year is divisible by 4 boolean isleapyear = (year % 4 == 0); // A leap year is divisible by 4 but not by 100 isleapyear = isleapyear && (year % 100!= 0); // A leap year is divisible by 4 but not by 100 or divisible by 400 isleapyear = isleapyear (year % 400 == 0); Or you can combine all these expressions into one like this: isleapyear = (year % 4 == 0 && year % 100!= 0) (year % 400 == 0); Determining Leap Year String s = JOptionPane.showInputDialog("Enter a year"); int year = Integer.parseInt(s); if (year % 4 == 0 && year % 100!= 0 year % 100 == 0) System.out.println("Leap"); else System.out.println("Not Leap"); Generating Random Numbers Java provides a static method random() in Math class to generate a random double value d such that 0.0 <= d < 1.0. Generating a Random Number double d = Math.random(); // d is a random number between 0.0 and 1.0, excluding 1.0 Thus, (int)(math.random() * 10) returns a random single-digit integer (i.e., a number between 0 and 9). Task 3 Use Math.random() to generate a random integer between 7 and 32. 8

switch Statements Java provides a switch statement to simplify coding for multiple conditions. It executes statements based on the value of a variable or an expression. The full syntax for the switch statement is: Syntax of Switch Statement switch (switch-expresion) { case value1: statement(s)1; case value2: statement(s)2;... case valuen: statement(s)n; default: statement(s)-for-default; } There are some rules for using switch statement: The switch-expression must yield a value of char, byte, short, int, or String 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. When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a break statement or the end of the switch statement is reached. The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. The keyword break is optional. The break statement immediately ends the switch statement. 9

Example: (you job depends on your birth month!) Write a program to let the user enter his birth month, then your program will output a job for him from a pre-defined list. Using Switch Statement String s = JOptionPane.showInputDialog("Enter your birth month"); int month = Integer.parseInt(s); switch (month) { case 1: JOptionPane.showMessageDialog(null, "Lawyer"); case 2: JOptionPane.showMessageDialog(null, "Carpenter"); case 3: JOptionPane.showMessageDialog(null, "Farmer"); case 4: JOptionPane.showMessageDialog(null, "Doctor"); case 5: JOptionPane.showMessageDialog(null, "Police Man"); case 6: JOptionPane.showMessageDialog(null, "Driver"); case 7: JOptionPane.showMessageDialog(null, "Teacher"); case 8: JOptionPane.showMessageDialog(null, "Builder"); case 9: JOptionPane.showMessageDialog(null, "Cooker"); case 10: JOptionPane.showMessageDialog(null, "Designer"); case 11: JOptionPane.showMessageDialog(null, "Engineer"); case 12: JOptionPane.showMessageDialog(null, "Photographer"); default: JOptionPane.showMessageDialog(null, "Fool man -_-"); } 10

Conditional Expressions A conditional expression is used to evaluate an expression based on a condition. The syntax is: result = boolean-expression? expression1 : expression2; If the value of boolean-expression is true, then result = expression1 If the value of boolean-expression is false, then result = expression2 For example: String number = (n % 2 == 0? Even : Odd ); number = Even, since the expression (n % 2 ==0) is true. 11

Operator Precedence and Associativity Operator precedence and associativity determine the order in which operators are evaluated. The following table lists in some operators in decreasing order of precedence from top to bottom. The logical operators have lower precedence than the relational operators and the relational operators have lower precedence than the arithmetic operators. 12

Netbeans Tips & Tricks CTRL + SHIFT + (UP/DOWN) Use this shortcut to duplicate the current line (or the selected lines). 13

Exercises: Part 1: Write a program that prompts the user to enter a decimal number and check if the fractional part is zero or not. Part 2: (Check ID Number Validity) A Palestinian ID Number consists of 9 digits: d 1 d 2 d 3 d 4 d 5 d 6 d 7 d 8 d 9.The last digit, d 9, is a checksum, which can be calculated from the other eight digits as following: ( ) Where { ( ) An ID number is valid only if the ninth digit matches the previous formula. Write a program that prompts the user to enter an ID number and displays if the number is valid or not. Here are sample runs: 14

Part 3: (Compute the perimeter of a triangle) Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise, display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the remaining edge. 15