bbs515 – nesneye yönelik programlamagonenc/courses/bbs515/lect3.pdf · boolean veri tipi ve...
TRANSCRIPT
BBS515 – Nesneye Yönelik ProgramlamaLecture 3: Kontrol Yapıları
19.10.2016
Prepared by: Gönenç Ercan
boolean Veri tipi ve Operatörleri
►Çoğu zaman iki değeri birbiriyle karşılaştırmamız gerekir. Mesela i değişkeninin değeri j’nin değerinden büyük mü öğrenmek isteriz. Java iki değeri karşılaştırmak için 6 operatör sağlamaktadır (relational operators). Karşılaştırmanın sonucu Boolean bir değer olarak döner: true veya false.
boolean b = (1 > 2);
2
Karşılaştırma Operatörleri
3
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Örnek Problem: Matematik Öğrenme Aracı
►Bir ilkokul öğrencisinin toplama çalışmak için kullanabileceği bir program yazıyoruz. İki rakamı rastgele seçip number1 ve number2 soru olarak «7 + 9 işleminin sonucu nedir?» yazdırmak istiyoruz. Öğrenci cevabı verdikten sonra trueveya false olarak cevabını değerlendirmemiz gerekiyor.
4
5
if (boolean-expression) { statement(s);
}
Boolean Expression
true
Statement(s)
false (radius >= 0)
true
area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area);
false
(A) (B)
if (radius >= 0) {area = radius * radius * PI;System.out.println("The area"
+ " for the circle of radius " + radius + " is " + area);
}
Not
6
if i > 0 { System.out.println("i is positive"); }
(a) Wrong (b) Correct
if (i > 0) { System.out.println("i is positive"); }
if (i > 0) { System.out.println("i is positive"); }
(a)
Equivalent
(b)
if (i > 0) System.out.println("i is positive");
if (i > 0) { System.out.println("i is positive"); }
(a)
Equivalent
(b)
if (i > 0) System.out.println("i is positive");
İki taraflı If ifadesiif (boolean-expression) {
statement(s)-for-the-true-case;}else {
statement(s)-for-the-false-case;}
7
Boolean Expression
false true
Statement(s) for the false case Statement(s) for the true case
if...else Örneğiif (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");
}
8
Birden fazla if İfadesi
9
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';
if-else ifadesinin takibi
10
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';
elsegrade = 'F';
Suppose score is 70.0 The condition is false
if-else ifadesinin takibi
11
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';
elsegrade = 'F';
Suppose score is 70.0
The condition is false
if-else ifadesinin takibi
12
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';
elsegrade = 'F';
Suppose score is 70.0
The condition is true
if-else ifadesinin takibi
13
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';
elsegrade = 'F';
Suppose score is 70.0
Grade is C
Not► Else ifadesi en son yazılmış if ifadesi ile eşleştirilir.
14
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
(b)
int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");
Not (devam)► Önceki örnekte herhangi bir çıktı verilmez. Else’in doğru ifade ile
eşleştirilebilmesi için süslü parantez kullanabiliriz.int i = 1; int j = 2;int k = 3;if (i > j) {
if (i > k)System.out.println("A");
}else
System.out.println("B");
15
Sık Yapılan Hatalardan Birisi► İf ifadesinin sonuna ; koymak.if (radius >= 0);{area = radius*radius*PI;System.out.println("The area for the circle of radius " +radius + " is " + area);
}► Bir derleme hatası (compilation) değil, mantık hatasıdır. Bu yüzden bulması
zor olabilir.► Bu hatayı daha çok süslü parantezi bir alt satırda tanımladığınızda
yapabilirsiniz.
16
Wrong
TIP
17
if (number % 2 == 0) even = true; else even = false;
(a)
Equivalent boolean even = number % 2 == 0; (b)
CAUTION
18
if (even == true) System.out.println( "It is even.");
(a)
Equivalent if (even) System.out.println( "It is even.");
(b)
Problem 2: Çıkartma işlemi► Program bu sefer çıkartma işlemini öğrenciye soracak. Bu durumda
rastgele seçilen iki sayıdan büyük olanı bulup soruyu ona göre sormamız gerekiyor. “9 – 2 işleminin sonucu nedir?” sorusunu öğrenciye sorduktan sonra mesaj olarak «Tebrikler doğru» veya «Yanlış buldunuz, cevap 7 olmalıydı» yazdırmalıyız.
19
Problem: Vücüt Kütle Dizini► Vücüt Kütle Dizini (BMI) ağırlık ve sağlık arasındaki ilişkiyi ölçmeye
yarar. kilograms cinsinden ağırlığın, metre cinsinden boya bölünmesi ile hesaplanır. Aşağıda 16 yaş ve üstü için çıkan değerin nasıl okunması gerektiği verilmektedir.
20
BMI Interpretation below 16 serious underweight
16-18 underweight 18-24 normal weight 24-29 overweight 29-35 seriously overweight above 35 gravely overweight
Mantıksal Operatörler
21
Operator Name
! not
&& and
|| or
^ exclusive or
Truth Table for Operator !
22
p !p
true false
false true
Example (assume age = 24, gender = 'M')
!(age > 18) is false, because (age > 18) is true.
!(gender != 'F') is true, because (grade != 'F') is false.
Truth Table for Operator &&
23
p1 p2 p1 && p2
false false false
false true false
true false false
true true true
Example (assume age = 24, gender = 'F')
(age > 18) && (gender == 'F') is true, because (age > 18) and (gender == 'F') are both true.
(age > 18) && (gender != 'F') is false, because (gender != 'F') is false.
Truth Table for Operator ||
24
p1 p2 p1 || p2
false false false
false true true
true false true
true true true
Example (assume age = 24, gender = 'F')
(age > 34) || (gender == 'F') is true, because (gender == 'F') is true.
(age > 34) || (gender == 'M') is false, because (age > 34) and (gender == 'M') are both false.
Truth Table for Operator !
25
p !p
true false
false true
Example
!(1 > 2) is true, because (1 > 2) is false.
!(1 > 0) is false, because (1 > 0) is true.
Truth Table for Operator &&
26
p1 p2 p1 && p2
false false false
false true false
true false false
true true true
Example
(3 > 2) && (5 >= 5) is true, because (3 > 2) and (5 >= 5) are both true.
(3 > 2) && (5 > 5) is false, because (5 > 5) is false.
Truth Table for Operator ||
27
p1 p2 p1 || p2
false false false
false true true
true false true
true true true
Example
(2 > 3) || (5 > 5) is false, because (2 > 3) and (5 > 5) are both false.
(3 > 2) || (5 > 5) is true, because (3 > 2) is true.
Truth Table for Operator ^
28
p1 p2 p1 ^ p2
false false false
false true true
true false true
true true false
Example (assume age = 24, gender = 'F')
(age > 34) ^ (gender == 'F') is true, because (age > 34) is false but (gender == 'F') is true.
(age > 34) || (gender == 'M') is false, because (age > 34) and (gender == 'M') are both false.
ExamplesSystem.out.println("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));
System.out.println("Is " + number + " divisible by 2 or 3? " +
((number % 2 == 0) || (number % 3 == 0)));
System.out.println("Is " + number +
" divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0)));
29
The & and | OperatorsIf x is 1, what is x after this expression?(x > 1) & (x++ < 10)
If x is 1, what is x after this expression?(1 > x) && ( 1 > x++)
How about (1 == x) | (10 > x++)?(1 == x) || (10 > x++)?
30
switch Statementsswitch (status) {case 0: compute taxes for single filers;
break;case 1: compute taxes for married file jointly;
break;case 2: compute taxes for married file separately;
break;case 3: compute taxes for head of household;
break;default: System.out.println("Errors: invalid status");
System.exit(0);}
31
switch Statement Flow Chart
32
status is 0 Compute tax for single filers break
Compute tax for married file jointly break status is 1
Compute tax for married file separatly break status is 2
Compute tax for head of household break status is 3
Default actions default
Next Statement
switch Statement Rules
33
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;
}
switch-expression sadece char, byte, short, or int veri tiplerinde olmalı ve parantez içine alınmalı
value1, ..., ve valueN değerlerininswitch-expression veri tipinden olması gerekir. Değere denk gelen case ifadesinin içindeki statemenlarçalıştırılır. value1, ..., and valueNifadeleri sabit olmalıdır, yani ifadeler değişken içermemelidir, örnek: 1 + x kullanılamaz.
34
switch Statement Rulesbreak satırı zorunlu değildir, ama her bir case sonunda kullanılırsa değere uygun ifade çalıştırıldıktan sonra diğer case ifadeleri kontrol edilmez. Eğer break kullanılmadıysa, bir sonraki case ifadesinden çalışmaya devam eder.
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;
}
default case, zorunlu değildir, eğer o satır çalıştırılırsa koşulsuz olarak kabul edilir ve içerisindeki işlemler yapılır.
Trace switch statement
35
switch (ch) {case 'a': System.out.println(ch);case 'b': System.out.println(ch);case 'c': System.out.println(ch);
}
Suppose ch is 'a':
Trace switch statement
36
switch (ch) {case 'a': System.out.println(ch);case 'b': System.out.println(ch);case 'c': System.out.println(ch);
}
ch is 'a':
Trace switch statement
37
switch (ch) {case 'a': System.out.println(ch);case 'b': System.out.println(ch);case 'c': System.out.println(ch);
}
Execute this line
Trace switch statement
38
switch (ch) {case 'a': System.out.println(ch);case 'b': System.out.println(ch);case 'c': System.out.println(ch);
}
Execute this line
Trace switch statement
39
switch (ch) {case 'a': System.out.println(ch);case 'b': System.out.println(ch);case 'c': System.out.println(ch);
}
Execute this line
Trace switch statement
40
switch (ch) {case 'a': System.out.println(ch);case 'b': System.out.println(ch);case 'c': System.out.println(ch);
}
Next statement;
Execute next statement
Trace switch statement
41
switch (ch) {case 'a': System.out.println(ch);
break;case 'b': System.out.println(ch);
break;case 'c': System.out.println(ch);
}
Suppose ch is 'a':
Trace switch statement
42
switch (ch) {case 'a': System.out.println(ch);
break;case 'b': System.out.println(ch);
break;case 'c': System.out.println(ch);
}
ch is 'a':
Trace switch statement
43
switch (ch) {case 'a': System.out.println(ch);
break;case 'b': System.out.println(ch);
break;case 'c': System.out.println(ch);
}
Execute this line
Trace switch statement
44
switch (ch) {case 'a': System.out.println(ch);
break;case 'b': System.out.println(ch);
break;case 'c': System.out.println(ch);
}
Execute this line
Trace switch statement
45
switch (ch) {case 'a': System.out.println(ch);
break;case 'b': System.out.println(ch);
break;case 'c': System.out.println(ch);
}
Next statement;
Execute next statement
Koşul Operatörüif (x > 0) y = 1
else y = -1;
► is equivalent toy = (x > 0) ? 1 : -1;(boolean-expression) ? expression1 : expression2
► Ternary operator► Binary operator► Unary operator
46
Koşul Operatörüif (num % 2 == 0)System.out.println(num + “is even”);
else System.out.println(num + “is odd”);
System.out.println((num % 2 == 0)? num + “is even” :num + “is odd”);
47
Koşul Operatörü, cont.► (boolean-expression) ? exp1 : exp2
48
Formatting Output ► Çıktı verirken printf statement kullanılabilir.
System.out.printf(format, items);
► Format bir dizge olup, mesaji ve düzenleme ifadeciklerini içermektedir. Bir düzenleme ifadeciği bir ifadenin nasıl gösterilmesi gerektiğini gösterir. Bir ifade numerik değer, character, boolean veya dizge olabilir. Düzenleme ifadecikleri % işareti ile başlar.
49
Frequently-Used Specifiers
50
Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in standard scientific notation 4.556000e+01
%s a string "Java is cool"
int count = 5;
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
display count is 5 and amount is 45.560000
items
Operator Precedence► var++, var--► +, - (Unary plus and minus), ++var,--var► (type) Casting► ! (Not)► *, /, % (Multiplication, division, and remainder)► +, - (Binary addition and subtraction)► <, <=, >, >= (Comparison)► ==, !=; (Equality) ► ^ (Exclusive OR) ► && (Conditional AND) Short-circuit AND► || (Conditional OR) Short-circuit OR► =, +=, -=, *=, /=, %= (Assignment operator)
51
Operator Precedence and Associativity► Parantez işlem önceliğine sahiptir. Önce parantez içindeki ifade
çalıştırılır. Eğer parantez yoksa operatörlerin önceliğine göre ifade çalıştırılır.
► Eğer ifadede aynı önceliğe sahip operatör varsa, operatörlerin tanımlı yönüne göre ifade değerlendirilir. Bütün ikili operatörler (atama dışında) soldan sağa okunur.
52
Operator Associativity► Aşağıdaki gibi bir ifade soldan okunacağı için aşağıdaki parantez
sırasına göre değerlendirilebilir.a – b + c – d is equivalent to ((a – b) + c) – d
► Atama operatörü sağdan okunur. Bu yüzden aşağıdaki örnek işleme sırası aşağıda verildiği gibi olur.a = b += c = 5 is equivalent to a = (b += (c = 5))
53
Example► 3 + 4 * 4 > 5 * (4 + 3) - 1 aşağıdaki gibi değerlendirilir:
54
3 + 4 * 4 > 5 * (4 + 3) - 1 3 + 4 * 4 > 5 * 7 – 1 3 + 16 > 5 * 7 – 1 3 + 16 > 35 – 1 19 > 35 – 1 19 > 34 false
(1) inside parentheses first
(2) multiplication
(3) multiplication
(4) addition
(5) subtraction
(6) greater than
Loops
Opening Problem► Problem:
56
System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");
… … … System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");
100 times
Introducing while Loops
57
int count = 0;while (count < 100) {
System.out.println("Welcome to Java");count++;
}
while Loop Flow Chart
58
while (loop-continuation-condition) {
// loop-body;
Statement(s);
}
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
}
Loop Continuation Condition?
true
Statement(s) (loop body)
false (count < 100)?
true
System.out.println("Welcome to Java!"); count++;
false
(A) (B)
count = 0;
Trace while Loop
59
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Initialize count
Trace while Loop, cont.
60
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is true
Trace while Loop, cont.
61
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
Trace while Loop, cont.
62
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1count is 1 now
Trace while Loop, cont.
63
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is still true since count is 1
Trace while Loop, cont.
64
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
Trace while Loop, cont.
65
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1count is 2 now
Trace while Loop, cont.
66
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is false since count is 2 now
Trace while Loop
67
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
The loop exits. Execute the next statement after the loop.
Caution► Don’t use floating-point values for equality checking in a loop control. Since floating-point values
are approximations for some values, using them could result in imprecise counter values and inaccurate results. Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1:
double item = 1; double sum = 0;while (item != 0) { // No guarantee item will be 0
sum += item;item -= 0.1;
}System.out.println(sum);
► Variable item starts with 1 and is reduced by 0.1 every time the loop body is executed. The loop should terminate when item becomes 0. However, there is no guarantee that item will be exactly 0, because the floating-point arithmetic is approximated. This loop seems OK on the surface, but it is actually an infinite loop. 68
do-while Loop
69
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
Loop Continuation Condition?
true
Statement(s) (loop body)
false
70
for Loopsfor (initial-action; loop-continuation-condition; action-after-each-iteration) {// loop body;Statement(s);
}
int i;for (i = 0; i < 100; i++) {
System.out.println("Welcome to Java!");
}
Loop Continuation Condition?
true Statement(s) (loop body)
false
(A)
Action-After-Each-Iteration
Initial-Action
(i < 100)?
true System.out.println( "Welcome to Java");
false
(B)
i++
i = 0
Trace for Loop
71
int i;for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Declare i
Trace for Loop, cont.
72
int i;for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Execute initializeri is now 0
Trace for Loop, cont.
73
int i;for (i = 0; i < 2; i++) {System.out.println( "Welcome to Java!");
}
(i < 2) is true since i is 0
Trace for Loop, cont.
74
int i;for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!"); }
Print Welcome to Java
Trace for Loop, cont.
75
int i;for (i = 0; i < 2; i++) {System.out.println("Welcome to Java!");
}
Execute adjustment statement i now is 1
Trace for Loop, cont.
76
int i;for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!"); }
(i < 2) is still true since i is 1
Trace for Loop, cont.
77
int i;for (i = 0; i < 2; i++) {System.out.println("Welcome to Java!");
}
Print Welcome to Java
Trace for Loop, cont.
78
int i;for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!"); }
Execute adjustment statement i now is 2
Trace for Loop, cont.
79
int i;for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!"); }
(i < 2) is false since i is 2
Trace for Loop, cont.
80
int i;for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!"); }
Exit the loop. Execute the next statement after the loop
Note► The initial-action in a for loop can be a list of zero or more comma-
separated expressions. The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements. Therefore, the following two for loops are correct. They are rarely used in practice, however.for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
81
Note► If the loop-continuation-condition in a for loop is omitted, it is
implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion:
82
for ( ; ; ) { // Do something } (a)
Equivalent while (true) { // Do something }
(b)
Caution► Adding a semicolon at the end of the for clause before the loop body
is a common mistake, as shown below:
83
Logic Error
for (int i=0; i<10; i++);{System.out.println("i is " + i);
}
Caution, cont.► Similarly, the following loop is also wrong:int i=0; while (i < 10);{
System.out.println("i is " + i);i++;
}► In the case of the do loop, the following semicolon is needed to end the loop.int i=0; do {
System.out.println("i is " + i);i++;
} while (i<10);
84
Logic Error
Correct
Which Loop to Use?
85
The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b):
A for loop in (a) in the following figure can generally be converted into the following while loop in (b)
for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; }
(a)
Equivalent
(b)
initial-action; while (loop-continuation-condition) { // Loop body; action-after-each-iteration; }
while (loop-continuation-condition) { // Loop body }
(a)
Equivalent
(b)
for ( ; loop-continuation-condition; ) // Loop body }