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