Upload
vanhuong
View
214
Download
1
Embed Size (px)
Citation preview
Islamic University of Gaza
Faculty of Engineering
Computer Engineering Dept.
Computer Programming Lab (ECOM 2114)
Lab 3
Selections
Eng. Mohammed Alokshiya
October 19, 2014
2
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;
3
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.
Narrowing float f = 10.2f;
int i = (int)f;
// i = 10
4
boolean Data Type
The boolean data type declares a variable with the value either
true or false.
Example boolean b = true;
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).
5
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.
6
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 implement
7
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.
8
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.
9
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;
break;
case value2:
statement(s)2;
break;
...
case valueN:
statement(s)N;
break;
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.
10
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");
break;
case 2:
JOptionPane.showMessageDialog(null, "Carpenter");
break;
case 3:
JOptionPane.showMessageDialog(null, "Farmer");
break;
case 4:
JOptionPane.showMessageDialog(null, "Doctor");
break;
case 5:
JOptionPane.showMessageDialog(null, "Police Man");
break;
case 6:
JOptionPane.showMessageDialog(null, "Driver");
break;
case 7:
JOptionPane.showMessageDialog(null, "Teacher");
break;
case 8:
JOptionPane.showMessageDialog(null, "Builder");
break;
case 9:
JOptionPane.showMessageDialog(null, "Cooker");
break;
case 10:
JOptionPane.showMessageDialog(null, "Designer");
break;
case 11:
JOptionPane.showMessageDialog(null, "Engineer");
break;
case 12:
JOptionPane.showMessageDialog(null, "Photographer");
break;
default:
JOptionPane.showMessageDialog(null, "Fool man -_-");
}
11
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.
12
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.
13
Netbeans Tips & Tricks
CTRL + SHIFT + (UP/DOWN) Use this shortcut to duplicate the current line (or the selected lines).
14
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: d1d2d3d4d5d6d7d8d9.The last digit, d9, is a
checksum, which can be calculated from the other eight digits as
following:
𝑑9 = (𝑑1 + 𝑑3 + 𝑑5 + 𝑑7 + 𝑥2 + 𝑥4 + 𝑥6 + 𝑥8) ∗ 9 % 10
Where 𝑥𝑛 = {𝑑𝑛 ∗ 2 𝑤ℎ𝑒𝑛 𝑑𝑛 < 5(𝑑𝑛 − 5) ∗ 2 + 1 𝑤ℎ𝑒𝑛 𝑑𝑛 ≥ 5
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: