JavaJava · Chapterبەش 5 · Lectureوانە 5.1
Comparisons, Booleans and if…elseبەراوردکردن، بوولیانەکان و if…else
Making decisions in Java: booleans and boolean expressions, the six comparison operators (==, !=, >, <, >=, <=), the one-way if and the two-way if … else with their flowcharts, two separate ifs, a boolean read from the keyboard, checking input with hasNextInt, and the classic mistakes: missing braces, a semicolon after if, = instead of ==, and comparing decimals or strings with ==.
بڕیاردان لە Javaـدا: و ، شەش (==، !=، >، <، >=، <=)، ifـی یەک ڕێگا و if … elseـی دوو ڕێگا لەگەڵ ، دوو ifـی جیاواز، کە لە دەخوێنرێتەوە، پشکنینی بە hasNextInt و هەڵە کلاسیکییەکان: کەوانەی ون، لە دوای if، = لە جیاتی == و بەراوردکردنی یان بە ==.
What you will learnچی فێر دەبیت
- Write boolean expressions with the six comparison operators and keep their results in
booleanvariables. - Use a one-way
ifand a two-wayif … else, and follow them on a flowchart. - Find and fix the classic
ifmistakes: missing braces, a;after the condition,=instead of==.
- بە شەش بنووسیت و ئەنجامەکانیان لە
booleanـدا هەڵبگریت. ifـی یەک ڕێگا وif … elseـی دوو ڕێگا بەکار بهێنیت و لەسەر بەدوایاندا بڕۆیت.- هەڵە کلاسیکییەکانی
ifبدۆزیتەوە و چاکیان بکەیتەوە: کەوانەی ون،;لە دوای ،=لە جیاتی==.
Programs that decideبڕیاردان لە بەرنامەدا
Until now every statement ran, one after the other. Real programs choose: if it is raining, take an umbrella; otherwise, wear a cap. The is the most basic of Java: it runs a block of code only if a is true, so the program decides while it runs which statements to execute.
تا ئێستا هەموو یەک لە دوای یەک جێبەجێ دەبوون. هەڵدەبژێرن: ئەگەر باران دەبارێت، چەترەکەت ببە؛ ئەگەر نا، کڵاوەکەت لەسەر بکە. سادەترین Javaـیە: تەنیا کاتێک جێبەجێ دەکات کە ڕاست بێت، بۆیە لە کاتی کارکردندا بڕیار دەدات چی جێبەجێ بکات.
Java has four shapes of if: the one-way if and the two-way if … else in this lesson; the nested if and the multi-way if … else if … else in Logical operators, nested and multi-way if. Each shape is drawn with the decision diamond of a (Flowchart symbols).
Java چوار شێوەی ifـی هەیە: ifـی یەک ڕێگا و if … elseـی دوو ڕێگا لەم وانەیەدا؛ و if … else if … elseـی فرە ڕێگا لە کارپێکەرە لۆجیکییەکان، ڕستەکانی ifـی ناوەکی و ifـی فرە ڕێگاـدا. هەر شێوەیەک بە ئەڵماسی بڕیاری دەکێشرێت (هێماکانی هێڵکاریی ڕەوت).
true or false: boolean expressionsڕاست یان هەڵە: دەربڕینە بوولییەکان
A condition must be a : an expression whose value is true or false, the two values of the type boolean (boolean). A comparison such as age >= 18 is the usual example. You can print the answer, or keep it in a boolean variable with a clear name:
دەبێت بێت: کە true یان falseـە، دوو جۆری boolean (boolean). بەراوردێکی وەک age >= 18 نموونە باوەکەیە. دەتوانیت وەڵامەکە چاپ بکەیت، یان لە booleanـدا بە ناوێکی ڕوون هەڵیبگریت:
public class VotingAge {
public static void main(String[] args) {
final int VOTING_AGE = 18;
int age = 17;
boolean canVote = age >= VOTING_AGE;
System.out.println("Can vote at " + age + ": " + canVote);
age = 18;
canVote = age >= VOTING_AGE;
System.out.println("Can vote at " + age + ": " + canVote);
}
}$ java VotingAge Can vote at 17: false Can vote at 18: true
A boolean variable can be the whole condition: if (canVote) means the same as if (canVote == true) and reads better. Python has the same idea with True and False (True and False).
boolean دەتوانێت هەموو بێت: if (canVote) هەمان واتای if (canVote == true)ـی هەیە و باشتر دەخوێنرێتەوە. Python هەمان بیرۆکەی بە True و False هەیە (True و False).
Six comparison operatorsشەش کارپێکەری بەراوردکردن
A compares two values; depending on how they relate, the result is true or false. Java has six. With a = 10 and b = 20:
دوو بەراورد دەکات؛ بەپێی پەیوەندییان، ئەنجامەکە true یان falseـە. Java شەشی هەیە. کاتێک a = 10 و b = 20:
| Operator | Meaningواتا | In mathsلە بیرکاریدا | Exampleنموونە | Resultئەنجام |
|---|---|---|---|---|
== | equal toیەکسانە بە | a == b | false | |
!= | not equal toیەکسان نییە بە | a != b | true | |
> | greater thanگەورەترە لە | a > b | false | |
< | less thanبچووکترە لە | a < b | true | |
>= | greater than or equal toگەورەترە یان یەکسانە بە | a >= b | false | |
<= | less than or equal toبچووکترە یان یەکسانە بە | a <= b | true |
The maths signs , and are written with two keys in code: !=, >=, <= (Equals and other relations). The same four checks with x = 5 and y = 3:
نیشانەکانی بیرکاری ، و لە کۆددا بە دوو دوگمە دەنووسرێن: !=، >=، <= (یەکسان و پەیوەندییەکانی تر). هەمان چوار پشکنین کاتێک x = 5 و y = 3:
public class CompareXY {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x == y); // is 5 equal to 3?
System.out.println(x != y); // is 5 not equal to 3?
System.out.println(x > y); // is 5 greater than 3?
System.out.println(x <= y); // is 5 less than or equal to 3?
}
}$ java CompareXY false true true false
Six comparison operatorsشەش کارپێکەری بەراوردکردن
Careful with == on decimals and on stringsئاگادار بە لە == لەگەڵ ژمارە کەرتییەکان و زنجیرەنووسەکان
== asks for exactly the same value. A decimal result is often a tiny bit off (Precision), so 0.1 + 0.2 == 0.3 is false. Compare decimals with a small tolerance instead: is the distance between them tiny?
== داوای ڕێک هەمان دەکات. ئەنجامی ژماردنی زۆرجار کەمێک جیاوازە (وردی)، بۆیە 0.1 + 0.2 == 0.3 falseـە. لە جیاتی ئەوە بە جیاوازییەکی بچووکی ڕێگەپێدراو بەراورد بکە: ئایا دووریی نێوانیان زۆر بچووکە؟
public class CompareDoubles {
public static void main(String[] args) {
double sum = 0.1 + 0.2;
System.out.println(sum);
System.out.println(sum == 0.3);
System.out.println(Math.abs(sum - 0.3) < 1e-9);
}
}$ java CompareDoubles 0.30000000000000004 false true
The one-way ififـی یەک ڕێگا
A one-way if runs its block if and only if the condition is true. If the condition is false, nothing is done and the program goes on after the block. The condition always stands in brackets:
ifـی یەک ڕێگا تەنیا و تەنیا کاتێک جێبەجێ دەکات کە ڕاست بێت. ئەگەر هەڵە بێت، هیچ ناکرێت و لە دوای بلۆکەکە بەردەوام دەبێت. هەمیشە لەناو کەوانەدایە:
if (boolean-expression) {
statement(s);
}public class IfExample {
public static void main(String[] args) {
int age = 20;
if (age > 18) {
System.out.println("Age is greater than 18");
}
}
}$ java IfExample Age is greater than 18
With int age = 18; and a last line System.out.println("Done"); the same program prints only Done: 18 is not greater than 18. Use >= when the limit itself counts.
بە int age = 18; و دێڕێکی کۆتایی System.out.println("Done");، هەمان تەنیا Done چاپ دەکات: 18 لە 18 گەورەتر نییە. کاتێک خودی سنوورەکە حیساب دەکرێت >= بەکار بهێنە.
The one-way ififـی یەک ڕێگا
Area only for a sensible radiusڕووبەر تەنیا بۆ نیوەتیرەیەکی گونجاو
A circle cannot have a negative radius, so this program computes the area only when radius >= 0. For a negative input it prints nothing after the prompt:
بازنە ناتوانێت نیوەتیرەی نەرێنیی هەبێت، بۆیە ئەم ڕووبەرەکە تەنیا کاتێک دەژمێرێت کە radius >= 0 بێت. بۆ نەرێنی، لە دوای هیچ چاپ ناکات:
import java.util.Scanner;
public class RadiusCal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the radius: ");
double radius = input.nextDouble();
if (radius >= 0) {
double area = Math.pow(radius, 2) * Math.PI;
System.out.println("The area for the circle of radius " + radius + " is " + area);
}
}
}$ java RadiusCal Enter the radius: 2 The area for the circle of radius 2.0 is 12.566370614359172 $ java RadiusCal Enter the radius: -2
Math.pow(radius, 2) squares the radius and Math.PI is π to 15 decimal places (Math.PI). With a rough final double PI = 3.14; the area for 2 comes out as 12.56 instead of 12.566370614359172.
Math.pow(radius, 2) نیوەتیرەکە دووجا دەکات و Math.PI بریتییە لە π بە 15 (Math.PI). بە final double PI = 3.14;ـی نزیککراو، ڕووبەری 2 دەبێتە 12.56 لە جیاتی 12.566370614359172.
The one-way ififـی یەک ڕێگا
Two separate ifsدوو ifـی جیاواز
Each if makes its own decision. Here both conditions are tested for every number, so zero, one or two messages can appear. % gives the remainder (Remainder): a number is divisible by 5 when number % 5 == 0. With a single statement the braces may be left out (Braces):
هەر ifـێک بڕیاری خۆی دەدات. لێرەدا هەردوو بۆ هەموو ژمارەیەک دەپشکنرێن، بۆیە سفر، یەک یان دوو پەیام دەکرێت دەربکەون. % دەدات (پاشماوە): ژمارەیەک بەسەر 5دا دابەش دەبێت کاتێک number % 5 == 0. بە یەک دەکرێت کەوانەکان لابدرێن (کەوانەکان):
import java.util.Scanner;
public class IntNum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number % 5 == 0)
System.out.println("HiFive");
if (number % 2 == 0)
System.out.println("HiEven");
}
}$ java IntNum Enter an integer: 5 HiFive $ java IntNum Enter an integer: 60 HiFive HiEven $ java IntNum Enter an integer: 4 HiEven $ java IntNum Enter an integer: 7
Two ways: if … elseدوو ڕێگا: if … else
An gives the false case its own block. The if … else statement decides the path by the condition: exactly one of the two blocks runs, and then the program goes on after the whole statement.
بلۆکێکی تایبەت دەداتە حاڵەتی false. if … else بەپێی ڕێگاکە دیاری دەکات: تەنیا یەکێک لە دوو بلۆکەکە جێبەجێ دەبێت و پاشان لە دوای هەموو بەردەوام دەبێت.
if (boolean-expression) {
statement(s) for the true case;
} else {
statement(s) for the false case;
}import java.util.Scanner;
public class Umbrella {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Is it raining (true/false)? ");
boolean raining = input.nextBoolean();
if (raining) {
System.out.println("Take your umbrella.");
} else {
System.out.println("Wear your cap.");
}
System.out.println("Have a good day!");
}
}$ java Umbrella Is it raining (true/false)? true Take your umbrella. Have a good day! $ java Umbrella Is it raining (true/false)? false Wear your cap. Have a good day!
Two ways: if … elseدوو ڕێگا: if … else
if … else for the circleif … else بۆ بازنەکە
The two-way version of the circle program answers a negative radius too:
وەشانی دوو ڕێگای بازنەکە وەڵامی نیوەتیرەی نەرێنیش دەداتەوە:
import java.util.Scanner;
public class RadiusCal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the radius: ");
double radius = input.nextDouble();
if (radius >= 0) {
double area = Math.pow(radius, 2) * Math.PI;
System.out.printf("The area for the circle of radius %.1f is %.2f%n", radius, area);
} else {
System.out.println("Negative input");
}
}
}$ java RadiusCal Enter the radius: 2 The area for the circle of radius 2.0 is 12.57 $ java RadiusCal Enter the radius: -2 Negative input


Two ways: if … elseدوو ڕێگا: if … else
Check the input before reading itپشکنینی نێوخستە پێش خوێندنەوە
hasNextInt() gives a boolean (Look before you take), so it can be the condition of an if … else. The program reads the age only when a whole number is waiting, and otherwise explains what to type instead of crashing:
hasNextInt() دەداتەوە (سەیرکردن پێش وەرگرتن)، بۆیە دەتوانێت if … elseـێک بێت. تەنیا کاتێک تەمەنەکە دەخوێنێتەوە کە چاوەڕێ بکات؛ ئەگەر نا، لە جیاتی تێکشکان ڕوون دەکاتەوە چی بنووسرێت:
import java.util.Scanner;
public class SafeAge {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Age: ");
if (input.hasNextInt()) {
int age = input.nextInt();
System.out.println("Next year you will be " + (age + 1));
} else {
System.out.println("Please type a whole number, for example 20.");
}
}
}$ java SafeAge Age: 20 Next year you will be 21 $ java SafeAge Age: twenty Please type a whole number, for example 20.
hasNextInt() سەیر دەکات پێش ئەوەی nextInt() وەریبگرێتCêITTo ask again until the input is right you need a loop (while; a ready example: while (true) and break), or catch the exception (A safe input loop).
بۆ پرسینەوە تا دروست دەبێت پێویستت بە هەیە (while؛ نموونەیەکی ئامادە: while (true) و break)، یان بگرە (خولێکی سەلامەتی نێوخستە).
Braces make the blockکەوانەکان بلۆکی کۆدەکە دروست دەکەن
Braces { } group statements into a . With exactly one statement they may be left out, as in IntNum. But Java ignores : without braces only the first statement belongs to the if. Forgetting the braces around two statements is a classic error. Here the radius is −5:
کەوانەکانی { } کۆ دەکەنەوە لە . بە ڕێک یەک دەکرێت لابدرێن، وەک لە IntNumـدا. بەڵام Java گوێ بە نادات: بەبێ کەوانە تەنیا یەکەم سەر بە ifـەکەیە. لەبیرچوونی کەوانە بە دەوری دوو هەڵەیەکی کلاسیکییە. لێرەدا نیوەتیرەکە −5ـە:
public class MissingBraces {
public static void main(String[] args) {
double radius = -5;
double area = 0;
if (radius >= 0)
area = radius * radius * Math.PI;
System.out.println("The area is " + area);
}
}$ java MissingBraces The area is 0.0
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 7
Indented like the line above, but outside the if.
وەک دێڕی سەرەوە بۆشایی هەیە، بەڵام لە دەرەوەی ifـەکەدایە.
With braces around both lines, the same program prints nothing for −5. The safe habit: always write the braces, even for one statement; then a line added later cannot fall outside the if.
بە کەوانە بە دەوری هەردوو دێڕەکەدا، هەمان بۆ −5 هیچ چاپ ناکات. خووی سەلامەت: هەمیشە کەوانەکان بنووسە، تەنانەت بۆ یەک ؛ ئەوسا دێڕێک کە دواتر زیاد دەکرێت ناکەوێتە دەرەوەی ifـەکە.
A semicolon after if (…)خاڵبۆر لە دوای if (…)
A right after the condition ends the if at once. The ; alone is an empty statement, a statement that does nothing, and the if controls only that. The block under it is an ordinary block, and it always runs. Radius −5 again:
ڕاستەوخۆ لە دوای یەکسەر ifـەکە تەواو دەکات. ; بە تەنیا ڕستەیەکی بەتاڵە، کە هیچ ناکات؛ ifـەکە تەنیا کۆنترۆڵی ئەو دەکات. بلۆکی ژێرەوەی بلۆکێکی ئاساییە و هەمیشە جێبەجێ دەبێت. دیسان نیوەتیرەی −5:
public class SemicolonAfterIf {
public static void main(String[] args) {
double radius = -5;
double area;
if (radius >= 0); {
area = radius * radius * Math.PI;
System.out.println("The area is " + area);
}
}
}$ java SemicolonAfterIf
The area is 78.53981633974483
$ javac -Xlint:all SemicolonAfterIf.java
SemicolonAfterIf.java:5: warning: [empty] empty statement after if
if (radius >= 0); {
^
1 warningIt is neither a compile error nor a runtime error but a , so it is hard to find. javac -Xlint:all (and most editors) give the empty statement after if. Before an else the same ; becomes a compile error, 'else' without 'if' (Common mistakes).
نە و نە ، بەڵکو ، بۆیە دۆزینەوەی قورسە. javac -Xlint:all (و زۆربەی دەستکاریکەرەکان) empty statement after if دەدەن. پێش elseـێک هەمان ; دەبێتە : 'else' without 'if' (هەڵە باوەکان).
= stores, == compares= دادەنێت، == بەراورد دەکات
= is the : it stores a value (= is not equals). == asks a question. An if needs a boolean, so Java catches the mix-up when the variable is a number:
= : دادەنێت (= یەکسان نییە). == پرسیار دەکات. if پێویستی بە هەیە، بۆیە Java ئەم تێکەڵکردنە دەگرێت کاتێک ژمارەیە:
public class AssignInIf {
public static void main(String[] args) {
int x = 5;
if (x = 5) {
System.out.println("x is 5");
}
}
}$ javac AssignInIf.java
AssignInIf.java:4: error: incompatible types: int cannot be converted to boolean
if (x = 5) {
^
1 errorWith a boolean variable the mistake compiles: if (finished = true) stores true in finished, so the block always runs and the old value is lost:
بە boolean هەڵەکە کۆمپایل دەبێت: if (finished = true) true لە finishedـدا دادەنێت، بۆیە بلۆکەکە هەمیشە جێبەجێ دەبێت و ون دەبێت:
public class AssignBoolean {
public static void main(String[] args) {
boolean finished = false;
if (finished = true) {
System.out.println("Finished!");
}
System.out.println("finished is now " + finished);
}
}$ java AssignBoolean Finished! finished is now true
Write if (finished) for true and if (!finished) for false; ! is explained in the next lesson. The same slip in Python is a syntax error (= instead of ==).
بۆ true بنووسە if (finished) و بۆ false if (!finished)؛ ! لە وانەی داهاتوودا ڕوون دەکرێتەوە. هەمان هەڵە لە Pythonـدا (= لە جیاتی ==).
Common mistakesهەڵە باوەکان
| You wroteنووسیت | javac or the run saysjavac یان جێبەجێکردن دەڵێت | Fixچارەسەر |
|---|---|---|
If (x > 5) | ';' expected | if is lowercase.if بە پیتی بچووکە. |
if x > 5 { | '(' expected ')' expected | Brackets around the condition.کەوانە بە دەوری . |
if (x => 5) | illegal start of expression | >=, in that order.>=، بەم ڕیزبەندییە. |
if (0 < x < 10) | bad operand types for binary operator '<' | 0 < x && x < 10 (&&)0 < x && x < 10 (&&) |
if (x = 5) | incompatible types: int cannot be converted to boolean | ==== |
if (done = true) | always true, no messageهەمیشە true، بێ پەیام | if (done)if (done) |
if (n > 0); … else | 'else' without 'if' | Delete the ;.;ـەکە بسڕەوە. |
if (r >= 0); { … } | the block always runsبلۆکەکە هەمیشە جێبەجێ دەبێت | Delete the ;.;ـەکە بسڕەوە. |
| two statements, no bracesدوو ، بێ کەوانە | the second always runsدووەمیان هەمیشە جێبەجێ دەبێت | { } around both{ } بە دەوری هەردووکیاندا |
0.1 + 0.2 == 0.3 | false | Math.abs(a - b) < 1e-9Math.abs(a - b) < 1e-9 |
name == "Aram" | may be false for the same lettersڕەنگە بۆ هەمان پیت false بێت | name.equals("Aram") (Comparing strings)name.equals("Aram") (بەراوردکردنی زنجیرەنووسەکان) |
The real javac messages of the first four rows and of else without if:
پەیامە ڕاستەقینەکانی javac بۆ چوار ڕیزی یەکەم و بۆ elseـی بێ if:
$ javac CapitalIf.java
CapitalIf.java:4: error: ';' expected
If (x > 5) {
^
1 error
$ javac NoParentheses.java
NoParentheses.java:4: error: '(' expected
if x > 5 {
^
NoParentheses.java:4: error: ')' expected
if x > 5 {
^
2 errors
$ javac WrongOperator.java
WrongOperator.java:4: error: illegal start of expression
if (x => 5) {
^
1 error
$ javac Between.java
Between.java:4: error: bad operand types for binary operator '<'
if (0 < x < 10) {
^
first type: boolean
second type: int
1 error
$ javac ElseWithoutIf.java
ElseWithoutIf.java:6: error: 'else' without 'if'
else
^
1 errorPracticeڕاهێنان
Read a mark and print Pass for 50 or more, otherwise Fail. Test with 50 and 49.
نمرەیەک بخوێنەوە و بۆ 50 یان زیاتر Pass چاپ بکە، ئەگەر نا Fail. بە 50 و 49 تاقی بکەرەوە.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class PassFail {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Mark: ");
int mark = input.nextInt();
if (mark >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}$ java PassFail Mark: 50 Pass $ java PassFail Mark: 49 Fail
50 and 49 are the values on both sides of the limit; >= puts 50 on the pass side.
50 و 49 ئەو کە لە هەردوو لای سنوورەکەدان؛ >= 50 دەخاتە لای دەرچوون.
Read two whole numbers and print the larger one with an if … else.
دوو بخوێنەوە و بە if … else گەورەترەکەیان چاپ بکە.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class Larger {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Two whole numbers: ");
int a = input.nextInt();
int b = input.nextInt();
int larger;
if (a >= b) {
larger = a;
} else {
larger = b;
}
System.out.println("The larger number is " + larger);
}
}$ java Larger Two whole numbers: 12 9 The larger number is 12 $ java Larger Two whole numbers: 4 15 The larger number is 15 $ java Larger Two whole numbers: 6 6 The larger number is 6
Test equal numbers too: with >= the program prints 6 for 6 and 6. Math.max(a, b) does the same job (Math.max).
ژمارەی یەکسانیش تاقی بکەرەوە: بە >= بۆ 6 و 6 ژمارەی 6 چاپ دەکات. Math.max(a, b) هەمان کار دەکات (Math.max).
Children under 12 pay 1,000 dinars, everyone else 2,000. Read an age and print the price with %,d.
منداڵی خوار 12 ساڵ 1,000 دینار دەدەن، هەموو کەسێکی تر 2,000. تەمەنێک بخوێنەوە و نرخەکە بە %,d چاپ بکە.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class Ticket {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Age: ");
int age = input.nextInt();
int price;
if (age < 12) {
price = 1000;
} else {
price = 2000;
}
System.out.printf("Ticket: %,d dinars%n", price);
}
}$ java Ticket Age: 8 Ticket: 1,000 dinars $ java Ticket Age: 12 Ticket: 2,000 dinars $ java Ticket Age: 30 Ticket: 2,000 dinars
12 is the boundary: age < 12 is false for 12, so a 12-year-old pays the full price.
12 سنوورەکەیە: age < 12 بۆ 12 هەڵەیە، بۆیە منداڵێکی 12 ساڵان نرخی تەواو دەدات.
Read a whole number and print its distance from zero (its absolute value) using one if and no Math.
بخوێنەوە و دووریی لە سفرەوە () بە یەک if و بەبێ Math چاپ بکە.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class MyAbs {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Whole number: ");
int n = input.nextInt();
if (n < 0) {
n = -n;
}
System.out.println("Distance from zero: " + n);
}
}$ java MyAbs Whole number: -7 Distance from zero: 7 $ java MyAbs Whole number: 3 Distance from zero: 3
What does this print?
ئەمە چی چاپ دەکات؟
int t = 25;
if (t > 20) {
System.out.println("A");
}
if (t > 30) {
System.out.println("B");
} else {
System.out.println("C");
}
System.out.println("D");Show answerوەڵامەکە پیشان بدە
public class PredictIf {
public static void main(String[] args) {
int t = 25;
if (t > 20) {
System.out.println("A");
}
if (t > 30) {
System.out.println("B");
} else {
System.out.println("C");
}
System.out.println("D");
}
}$ java PredictIf A C D
t > 20 is true, so A; t > 30 is false, so the else prints C; D always prints.
t > 20 ڕاستە، بۆیە A؛ t > 30 هەڵەیە، بۆیە else C چاپ دەکات؛ D هەمیشە چاپ دەکرێت.
This program prints You get a 10% discount! for a price of 8000. Why, and how do you fix it?
ئەم بۆ نرخی 8000 You get a 10% discount! چاپ دەکات. بۆچی؟ چۆن چاکی دەکەیتەوە؟
public class Discount {
public static void main(String[] args) {
int price = 8000;
if (price > 10000);
{
System.out.println("You get a 10% discount!");
}
}
}$ java Discount You get a 10% discount!
Show answerوەڵامەکە پیشان بدە
The ; after if (price > 10000) is an empty statement, so the block always runs. Without it:
ئەو ;ـەی لە دوای if (price > 10000) ڕستەیەکی بەتاڵە، بۆیە بلۆکەکە هەمیشە جێبەجێ دەبێت. بەبێ ئەو:
public class Discount {
public static void main(String[] args) {
int price = 8000;
if (price > 10000) {
System.out.println("You get a 10% discount!");
}
System.out.println("Price: " + price);
}
}$ java Discount Price: 8000
Read two whole numbers and print their quotient, but print a message instead when the second number is 0.
دوو بخوێنەوە و دابەشکردنیان چاپ بکە، بەڵام کاتێک ژمارەی دووەم 0ـە لە جیاتی ئەوە پەیامێک چاپ بکە.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class SafeDivide {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Two whole numbers: ");
int a = input.nextInt();
int b = input.nextInt();
if (b != 0) {
System.out.println(a + " / " + b + " = " + a / b);
} else {
System.out.println("You cannot divide by zero.");
}
}
}$ java SafeDivide Two whole numbers: 17 5 17 / 5 = 3 $ java SafeDivide Two whole numbers: 17 0 You cannot divide by zero.
Without the check, 17 / 0 stops the program with ArithmeticException: / by zero (Runtime errors).
بەبێ پشکنینەکە، 17 / 0 بە ArithmeticException: / by zero دەوەستێنێت (هەڵەکانی کاتی جێبەجێکردن).
Summaryکورتە
- A condition is a boolean expression:
trueorfalse. Comparisons give booleans; abooleanvariable can be a condition. - Six comparison operators:
==!=><>=<=. Use a tolerance for doubles andequalsfor strings. - One-way
if (condition) { … }: the block runs or is skipped. Two-wayif … else: exactly one block runs. - Braces decide the block, not indentation. No
;afterif (…).=stores,==compares.
- :
trueیانfalse. بەراوردکردن دەدات؛booleanدەتوانێت بێت. - شەش :
==!=><>=<=. بۆ double ماوەی ڕێگەپێدراو و بۆequalsبەکار بهێنە. if (condition) { … }ـی یەک ڕێگا: بلۆکەکە جێبەجێ دەبێت یان تێدەپەڕێنرێت.if … elseـی دوو ڕێگا: ڕێک یەک بلۆک جێبەجێ دەبێت.- کەوانەکان بلۆکەکە دیاری دەکەن، نەک . هیچ
;لە دوایif (…)نەبێت.=دادەنێت و==بەراورد دەکات.
Why does if (x = 5) not compile in Java?بۆچی if (x = 5) لە Javaـدا کۆمپایل نابێت؟
x = 5 is an assignment whose value is the int 5, and an if needs a boolean.
x = 5 دانانی نرخە و intـی 5ـە، بەڵام if پێویستی بە هەیە.
What is printed by if (r >= 0); { System.out.println("A"); } when r is -1?if (r >= 0); { System.out.println("A"); } چی چاپ دەکات کاتێک r یەکسانە بە -1؟
A: the ; is an empty statement, and the block after it always runs.
A: ;ـەکە ڕستەیەکی بەتاڵە و بلۆکەکەی دوای هەمیشە جێبەجێ دەبێت.
When can the braces of an if be left out?کەی دەکرێت کەوانەکانی if لابدرێن؟
When the block has exactly one statement; writing them anyway is safer.
کاتێک بلۆکەکە ڕێک یەک هەیە؛ نووسینیان هەر سەلامەتترە.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Logical Operators, Nested and Multi-way ifکارپێکەرە لۆجیکییەکان، ڕستەکانی ifـی ناوەکی و ifـی فرە ڕێگا
Related lecturesوانە پەیوەندیدارەکان
- Logical Operators, Nested and Multi-way ifکارپێکەرە لۆجیکییەکان، ڕستەکانی ifـی ناوەکی و ifـی فرە ڕێگا
- Algorithms, Pseudocode and Flowchartsئەلگۆریزمەکان، نیمچەکۆد و هێڵکارییەکانی ڕەوت
- Making Decisions: if, elif, elseبڕیاردان:
if،elifوelse - Primitive Data Typesجۆرە سەرەتاییەکان
- Strings and String Methodsزنجیرەنووسەکان و میتۆدەکانی String
- Equals, Not Equal, Approximately and Other Relationsیەکسان، یەکسان نییە، نزیکەی یەکسان و پەیوەندییەکانی تر
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java Booleans
- W3Schools: Java Booleans, a real-life example
- W3Schools: Java Comparison Operators
- W3Schools: Java If … Else
- The Java Tutorials: Equality, Relational, and Conditional Operators
- The Java Tutorials: The if-then and if-then-else Statements
- Java Language Specification (Java SE 17), §14.6 The Empty Statement and §14.9 The if Statement
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.