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، = لە جیاتی == و بەراوردکردنی یان بە ==.

14 min read13 خولەک خوێندنەوە · 16 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Write boolean expressions with the six comparison operators and keep their results in boolean variables.
  • Use a one-way if and a two-way if … else, and follow them on a flowchart.
  • Find and fix the classic if mistakes: 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ـیە: تەنیا کاتێک جێبەجێ دەکات کە ڕاست بێت، بۆیە لە کاتی کارکردندا بڕیار دەدات چی جێبەجێ بکات.

A rain cloud above a decision diamond, Is it raining?, with the code if (raining). The true branch leads to an umbrella: Take your umbrella. The false branch leads to a cap: Wear your cap. Note: the answer, true or false, chooses one of the two actions.هەورێکی باران لە سەرووی ئەڵماسێکی بڕیار، باران دەبارێت؟، لەگەڵ کۆدی if (raining). لقی true بۆ چەترێک دەچێت: چەترەکەت ببە. لقی false بۆ کڵاوێک دەچێت: کڵاوەکەت لەسەر بکە. تێبینی: وەڵامەکە، true یان false، یەکێک لە دوو کارەکە هەڵدەبژێرێت.
One condition, two possible actionsیەک ، دوو کاری گونجاوCêIT

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ـدا بە ناوێکی ڕوون هەڵیبگریت:

VotingAge.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
The line boolean canVote = age >= 18; above an age line from 14 to 22. Ages 14 to 17 are marked false, ages 18 to 22 true. age = 17 gives false and age = 18 gives true. Note: >= includes the limit itself, so at 18 the answer is true.دێڕی boolean canVote = age >= 18; لە سەرووی هێڵێکی تەمەن لە 14 تا 22. تەمەنی 14 تا 17 false و 18 تا 22 true نیشانە کراون. age = 17 false دەدات و age = 18 true دەدات. تێبینی: سنوورەکە خۆی دەگرێتەوە، بۆیە لە 18دا وەڵامەکە true دەبێت.
A comparison gives a booleanبەراوردکردن دەداتCêIT

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:

OperatorMeaningواتاIn mathsلە بیرکاریداExampleنموونەResultئەنجام
==equal toیەکسانە بە==a == bfalse
!=not equal toیەکسان نییە بە≠\nea != btrue
>greater thanگەورەترە لە>>a > bfalse
<less thanبچووکترە لە<<a < btrue
>=greater than or equal toگەورەترە یان یەکسانە بە≥\gea >= bfalse
<=less than or equal toبچووکترە یان یەکسانە بە≤\lea <= btrue

The maths signs ≠\ne, ≥\ge and ≤\le are written with two keys in code: !=, >=, <= (Equals and other relations). The same four checks with x = 5 and y = 3:

نیشانەکانی بیرکاری ≠\ne، ≥\ge و ≤\le لە کۆددا بە دوو دوگمە دەنووسرێن: !=، >=، <= (یەکسان و پەیوەندییەکانی تر). هەمان چوار پشکنین کاتێک x = 5 و y = 3:

CompareXY.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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?
    }
}
A balance with 5 on the lower, heavier side and 3 on the higher side, and the six comparisons for x = 5 and y = 3 with their maths signs and results: x == y (=) false; x != y (≠) true; x > y (>) true; x < y (<) false; x >= y (≥) true; x <= y (≤) false.تەرازوویەک کە 5 لە لای قورستر و نزمتر و 3 لە لای بەرزترە، لەگەڵ شەش بەراوردەکە بۆ x = 5 و y = 3 بە نیشانەی بیرکاری و ئەنجامەکانیان: x == y (=) false؛ x != y (≠) true؛ x > y (>) true؛ x < y (<) false؛ x >= y (≥) true؛ x <= y (≤) false.
Each comparison operator gives true or falseهەر true یان false دەداتCêIT

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ـە. لە جیاتی ئەوە بە جیاوازییەکی بچووکی ڕێگەپێدراو بەراورد بکە: ئایا دووریی نێوانیان زۆر بچووکە؟

CompareDoubles.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
sum is 0.1 + 0.2 = 0.30000000000000004. On a magnified line, 0.3 and sum are two points with a tiny gap, both inside a tolerance band. sum == 0.3 gives false (not exactly equal); Math.abs(sum - 0.3) < 1e-9 gives true (close enough). The drawing is not to scale.sum بریتییە لە 0.1 + 0.2 = 0.30000000000000004. لەسەر هێڵێکی گەورەکراو، 0.3 و sum دوو خاڵن بە بۆشاییەکی زۆر بچووکەوە، هەردووکیان لەناو ماوەی ڕێگەپێدراودان. sum == 0.3 false دەدات (ڕێک یەکسان نین)؛ Math.abs(sum - 0.3) < 1e-9 true دەدات (بەئەندازەی پێویست نزیکن). وێنەکە بە پێوەر نییە.
Compare decimal results with a toleranceئەنجامی بە ماوەیەکی ڕێگەپێدراو بەراورد بکەCêIT

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ـی یەک ڕێگا تەنیا و تەنیا کاتێک جێبەجێ دەکات کە ڕاست بێت. ئەگەر هەڵە بێت، هیچ ناکرێت و لە دوای بلۆکەکە بەردەوام دەبێت. هەمیشە لەناو کەوانەدایە:

TEXT
if (boolean-expression) {
    statement(s);
}
IfExample.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class IfExample {
    public static void main(String[] args) {
        int age = 20;
        if (age > 18) {
            System.out.println("Age is greater than 18");
        }
    }
}
The code int age = 20; if (age > 18) { System.out.println("Age is greater than 18"); } System.out.println("Done"); next to its flowchart: after int age = 20; a diamond age > 18. The true arrow goes down to the println box and on to a join point; the false arrow goes around the box to the same join point. Then println("Done"). Note: age 20, the block runs; age 18, it is skipped and only Done appears.کۆدی int age = 20; if (age > 18) { System.out.println("Age is greater than 18"); } System.out.println("Done"); لە تەنیشت هێڵکاریی ڕەوتەکەی: لە دوای int age = 20; ئەڵماسێکی age > 18. تیری true بۆ خوارەوە دەچێت بۆ سندووقی println و پاشان بۆ خاڵێکی یەکگرتن؛ تیری false بە دەوری سندووقەکەدا دەچێت بۆ هەمان خاڵ. پاشان println("Done"). تێبینی: تەمەن 20، بلۆکەکە جێبەجێ دەبێت؛ تەمەن 18، تێدەپەڕێنرێت و تەنیا Done دەردەکەوێت.
One-way if: run the block, or skip itifـی یەک ڕێگا: جێبەجێ دەبێت یان تێدەپەڕێنرێتCêIT

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 بێت. بۆ نەرێنی، لە دوای هیچ چاپ ناکات:

RadiusCal.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
        }
    }
}

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. بە یەک دەکرێت کەوانەکان لابدرێن (کەوانەکان):

IntNum.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
    }
}
A table of four inputs: 5 gives true for number % 5 == 0 and false for number % 2 == 0, and prints HiFive; 60 gives true and true and prints HiFive and HiEven; 4 gives false and true and prints HiEven; 7 gives false and false and prints nothing. Note: with no else, zero, one or two messages can appear.خشتەیەکی چوار نێوخستە: 5 بۆ number % 5 == 0 true و بۆ number % 2 == 0 false دەدات و HiFive چاپ دەکات؛ 60 true و true دەدات و HiFive و HiEven چاپ دەکات؛ 4 false و true دەدات و HiEven چاپ دەکات؛ 7 false و false دەدات و هیچ چاپ ناکات. تێبینی: بێ else، سفر، یەک یان دوو پەیام دەکرێت دەربکەون.
Two separate ifs: each one decides on its ownدوو ifـی جیاواز: هەریەکەیان بە تەنیا بڕیار دەداتCêIT

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 بەپێی ڕێگاکە دیاری دەکات: تەنیا یەکێک لە دوو بلۆکەکە جێبەجێ دەبێت و پاشان لە دوای هەموو بەردەوام دەبێت.

TEXT
if (boolean-expression) {
    statement(s) for the true case;
} else {
    statement(s) for the false case;
}
Umbrella.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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!");
    }
}
The Umbrella code next to its flowchart: a diamond raining; the true branch leads to println("Take your umbrella."), the false branch to println("Wear your cap."). Both branches join and continue to println("Have a good day!"). Note: then the program goes on after the whole statement.کۆدی Umbrella لە تەنیشت هێڵکاریی ڕەوتەکەی: ئەڵماسێکی raining؛ لقی true بۆ println("Take your umbrella.") دەچێت و لقی false بۆ println("Wear your cap."). هەردوو لقەکە یەک دەگرنەوە و بەردەوام دەبن بۆ println("Have a good day!"). تێبینی: پاشان بەرنامەکە لە دوای هەموو ڕستەکە بەردەوام دەبێت.
if … else: exactly one of the two blocks runs⁦if … else⁩: تەنیا یەکێک لە دوو بلۆکەکە جێبەجێ دەبێتCêIT

Two ways: if … elseدوو ڕێگا: ⁦if … else⁩

if … else for the circle⁦if … else⁩ بۆ بازنەکە

The two-way version of the circle program answers a negative radius too:

وەشانی دوو ڕێگای بازنەکە وەڵامی نیوەتیرەی نەرێنیش دەداتەوە:

RadiusCal.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}
Animation. The user types 2: radius >= 0 is true, only the true block runs and the terminal shows The area for the circle of radius 2.0 is 12.57. In another run the user types -2: radius >= 0 is false and only the else block runs: Negative input.
Animation. The user types 2: radius >= 0 is true, only the true block runs and the terminal shows The area for the circle of radius 2.0 is 12.57. In another run the user types -2: radius >= 0 is false and only the else block runs: Negative input.
One value, one pathیەک ، یەک ڕێگاCêIT

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ـێک بێت. تەنیا کاتێک تەمەنەکە دەخوێنێتەوە کە چاوەڕێ بکات؛ ئەگەر نا، لە جیاتی تێکشکان ڕوون دەکاتەوە چی بنووسرێت:

SafeAge.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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.");
        }
    }
}
Look first, then read. Two typed inputs go through the same check, input.hasNextInt(). For 20 it answers true, so int age = input.nextInt(); runs and the program prints Next year you will be 21. For twenty it answers false, so the else block runs: nothing is read, nothing crashes, and the program prints Please type a whole number, for example 20. Note: the check only looks; it answers true or false and takes nothing.سەرەتا سەیر بکە، پاشان بیخوێنەوە. دوو نێوخستەی نووسراو بە هەمان پشکنیندا تێدەپەڕن، input.hasNextInt(). بۆ 20 وەڵامەکە true دەبێت، بۆیە int age = input.nextInt(); جێبەجێ دەبێت و بەرنامەکە Next year you will be 21 چاپ دەکات. بۆ twenty وەڵامەکە false دەبێت، بۆیە بلۆکی else جێبەجێ دەبێت: هیچ ناخوێنرێتەوە، هیچ تێکناشکێت و بەرنامەکە Please type a whole number, for example 20. چاپ دەکات. تێبینی: پشکنینەکە تەنیا سەیر دەکات؛ true یان false دەداتەوە و هیچ وەرناگرێت.
hasNextInt() looks before nextInt() takeshasNextInt() سەیر دەکات پێش ئەوەی nextInt() وەریبگرێتCêIT

To 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⁩ـە:

MissingBraces.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 7

Indented like the line above, but outside the if.

وەک دێڕی سەرەوە بۆشایی هەیە، بەڵام لە دەرەوەی ifـەکەدایە.

Two versions side by side. Without braces: only the area line is inside the if; the println line, although indented, is not. With braces: both lines are inside the block. For radius = -5 the first prints The area is 0.0 and the second prints nothing. Note: Java ignores the spaces at the start of a line.دوو وەشان لە تەنیشت یەک. بێ کەوانە: تەنیا دێڕی ڕووبەرەکە لەناو ifـەکەدایە؛ دێڕی println، هەرچەندە بۆشایی هەیە، لەناویدا نییە. بە کەوانەوە: هەردوو دێڕەکە لەناو بلۆکەکەدان. بۆ radius = -5، یەکەمیان The area is 0.0 چاپ دەکات و دووەمیان هیچ چاپ ناکات. تێبینی: Java گوێ بە بۆشایی سەرەتای دێڕ نادات.
Indentation does not make a block: braces do بلۆک دروست ناکات: کەوانەکان دروستی دەکەنCêIT

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⁩:

SemicolonAfterIf.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
        }
    }
}
The line if (radius >= 0); { with the semicolon marked: an empty statement, the only thing the if controls. The block below it is an ordinary block that always runs. For radius = -5 the program still prints The area is 78.53981633974483. javac -Xlint:all warns: [empty] empty statement after if.دێڕی if (radius >= 0); { و خاڵبۆرەکە نیشانە کراوە: ڕستەیەکی بەتاڵ، تاکە شتێک کە if کۆنترۆڵی دەکات. بلۆکی ژێرەوەی بلۆکێکی ئاساییە کە هەمیشە جێبەجێ دەبێت. بۆ radius = -5 بەرنامەکە هەر The area is 78.53981633974483 چاپ دەکات. javac -Xlint:all ئاگادار دەکاتەوە: [empty] empty statement after if.
A semicolon ends the if at once یەکسەر ifـەکە تەواو دەکاتCêIT

It 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 ئەم تێکەڵکردنە دەگرێت کاتێک ژمارەیە:

AssignInIf.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class AssignInIf {
    public static void main(String[] args) {
        int x = 5;
        if (x = 5) {
            System.out.println("x is 5");
        }
    }
}

With 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ـدا دادەنێت، بۆیە بلۆکەکە هەمیشە جێبەجێ دەبێت و ون دەبێت:

AssignBoolean.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
Left: x = 5; is assignment: put 5 into x, drawn as 5 going into the box x. Right: x == 5 is a comparison: is x equal to 5?, which gives true or false. Below: if (x = 5) { … } gives the compile error incompatible types: int cannot be converted to boolean.لای چەپ: x = 5; کارپێکەری دانانی نرخە: 5 بخە ناو x، وەک 5 کە دەچێتە ناو سندووقی x. لای ڕاست: x == 5 بەراوردکردنە: ئایا x یەکسانە بە 5؟، کە true یان false دەدات. لە خوارەوە: if (x = 5) { … } هەڵەی کاتی کۆمپایلکردنەکە incompatible types: int cannot be converted to boolean دەدات.
= stores a value, == asks a question= دادەنێت، == پرسیار دەکاتCêIT

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)';' expectedif is lowercase.if بە پیتی بچووکە.
if x > 5 {'(' expected ')' expectedBrackets 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.3falseMath.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:

Outputدەرئەنجام
$ 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 error

Practiceڕاهێنان

ExerciseڕاهێنانPass or failدەرچوو یان کەوتوو

Read a mark and print Pass for 50 or more, otherwise Fail. Test with 50 and 49.

نمرەیەک بخوێنەوە و بۆ ⁦50⁩ یان زیاتر Pass چاپ بکە، ئەگەر نا Fail. بە ⁦50⁩ و ⁦49⁩ تاقی بکەرەوە.

Show answerوەڵامەکە پیشان بدە
PassFail.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}

50 and 49 are the values on both sides of the limit; >= puts 50 on the pass side.

⁦50⁩ و ⁦49⁩ ئەو کە لە هەردوو لای سنوورەکەدان؛ >= ⁦50⁩ دەخاتە لای دەرچوون.

ExerciseڕاهێنانThe larger numberژمارە گەورەترەکە

Read two whole numbers and print the larger one with an if … else.

دوو بخوێنەوە و بە if … else گەورەترەکەیان چاپ بکە.

Show answerوەڵامەکە پیشان بدە
Larger.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}

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⁩).

ExerciseڕاهێنانBus ticketبلیتی پاس

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وەڵامەکە پیشان بدە
Ticket.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}

12 is the boundary: age < 12 is false for 12, so a 12-year-old pays the full price.

⁦12⁩ سنوورەکەیە: age < 12 بۆ ⁦12⁩ هەڵەیە، بۆیە منداڵێکی ⁦12⁩ ساڵان نرخی تەواو دەدات.

ExerciseڕاهێنانDistance from zeroدووری لە سفرەوە

Read a whole number and print its distance from zero (its absolute value) using one if and no Math.

بخوێنەوە و دووریی لە سفرەوە () بە یەک if و بەبێ Math چاپ بکە.

Show answerوەڵامەکە پیشان بدە
MyAbs.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
ExerciseڕاهێنانPredict the outputپێشبینیی دەرخستە بکە

What does this print?

ئەمە چی چاپ دەکات؟

JAVA
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وەڵامەکە پیشان بدە
PredictIf.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
    }
}

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 هەمیشە چاپ دەکرێت.

ExerciseڕاهێنانFind the bugباگەکە بدۆزەوە

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! چاپ دەکات. بۆچی؟ چۆن چاکی دەکەیتەوە؟

Discount.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Discount {
    public static void main(String[] args) {
        int price = 8000;
        if (price > 10000);
        {
            System.out.println("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) ڕستەیەکی بەتاڵە، بۆیە بلۆکەکە هەمیشە جێبەجێ دەبێت. بەبێ ئەو:

Discount.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
ExerciseڕاهێنانSafe divisionدابەشکردنی سەلامەت

Read two whole numbers and print their quotient, but print a message instead when the second number is 0.

دوو بخوێنەوە و دابەشکردنیان چاپ بکە، بەڵام کاتێک ژمارەی دووەم 0ـە لە جیاتی ئەوە پەیامێک چاپ بکە.

Show answerوەڵامەکە پیشان بدە
SafeDivide.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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.");
        }
    }
}

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: true or false. Comparisons give booleans; a boolean variable can be a condition.
  • Six comparison operators: == != > < >= <=. Use a tolerance for doubles and equals for strings.
  • One-way if (condition) { … }: the block runs or is skipped. Two-way if … else: exactly one block runs.
  • Braces decide the block, not indentation. No ; after if (…). = stores, == compares.
  • : true یان false. بەراوردکردن دەدات؛ boolean دەتوانێت بێت.
  • شەش : == != > < >= <=. بۆ double ماوەی ڕێگەپێدراو و بۆ equals بەکار بهێنە.
  • if (condition) { … }ـی یەک ڕێگا: بلۆکەکە جێبەجێ دەبێت یان تێدەپەڕێنرێت. if … elseـی دوو ڕێگا: ڕێک یەک بلۆک جێبەجێ دەبێت.
  • کەوانەکان بلۆکەکە دیاری دەکەن، نەک . هیچ ; لە دوای if (…) نەبێت. = دادەنێت و == بەراورد دەکات.
Review questionsپرسیارەکانی پێداچوونەوە
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زاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Logical Operators, Nested and Multi-way ifکارپێکەرە لۆجیکییەکان، ڕستەکانی ifـی ناوەکی و ifـی فرە ڕێگا

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.