JavaJava · Chapterبەش 5 · Lectureوانە 5.2

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

Combining conditions with &&, || and ! (booleans only), truth tables, precedence, short-circuit evaluation and the non-short-circuit & and |, De Morgan's laws, nested ifs and when && can replace them, the multi-way if … else if … else ladder with a 0–100 grade example, the dangling else, avoiding duplicate code, and the conditional operator ?:.

بەستنی بە &&، || و ! (تەنیا )، ، پێشینەیی، و & و |ـی بێ کورتبڕ، ، و کەی && دەتوانێت جێیان بگرێتەوە، پەیژەی فرە ڕێگای if … else if … else بە نموونەیەکی نمرەی 0 تا ⁦100⁩، ، دووربوون لە کۆدی دووپاتە و ?:.

20 min read18 خولەک خوێندنەوە · 21 stepsهەنگاو

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

  • Combine conditions with &&, || and !, read their truth tables, and use short-circuit evaluation as a guard.
  • Choose between nested ifs and an else if ladder, order the tests, and test the boundary values.
  • Avoid the dangling else and duplicate code, and write simple choices with ?:.
  • بە &&، || و ! ببەستیت، بخوێنیتەوە و وەک پاسەوان بەکار بهێنیت.
  • لە نێوان و پەیژەی else ifـدا هەڵبژێریت، پشکنینەکان ڕیز بکەیت و سنوور تاقی بکەیتەوە.
  • خۆت لە و کۆدی دووپاتە بپارێزیت و هەڵبژاردنی سادە بە ?: بنووسیت.

Two conditions at once: &&, || and !دوو مەرج پێکەوە: &&، ⁦||⁩ و !

Logical operators combine conditions. Is an age between 18 and 65? That is two comparisons that must both be true. Java has three ; with a = true and b = false:

پێکەوە دەبەستن. ئایا تەمەنێک لە نێوان ⁦18⁩ و ⁦65⁩دایە؟ ئەمە دوو بەراوردە کە دەبێت هەردووکیان ڕاست بن. Java سێ هەیە؛ کاتێک a = true و b = false:

OperatorNameناوTrue when …ڕاستە کاتێک …ExampleنموونەResultئەنجام
&&ANDboth sides are trueهەردوو لا ڕاست بنa && bfalse
||ORat least one side is trueلانیکەم لایەک ڕاست بێتa || btrue
!NOTits operand is false (it flips the value) هەڵە بێت ( پێچەوانە دەکاتەوە)!(a && b)true
AgeRange.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class AgeRange {
    public static void main(String[] args) {
        int age = 20;
        System.out.println(age >= 18 && age <= 65);
        age = 70;
        System.out.println(age >= 18 && age <= 65);
        System.out.println(age < 18 || age > 65);
    }
}
An age line from 0 to 90 with marks at 18 and 65. Above it, age >= 18 && age <= 65 is true only between 18 and 65 and false on both sides. Below it, age < 18 || age > 65 is true on both outer parts and false in the middle. Two dashed lines mark age 20 and age 70: && gives true for 20 and false for 70; || gives true for 70.هێڵێکی تەمەن لە 0 تا 90 بە نیشانەی 18 و 65. لە سەرەوە، age >= 18 && age <= 65 تەنیا لە نێوان 18 و 65دا ڕاستە و لە هەردوو لاکەی هەڵەیە. لە خوارەوە، age < 18 || age > 65 لە هەردوو بەشی دەرەوە ڕاستە و لە ناوەڕاست هەڵەیە. دوو هێڵی پچڕپچڕ تەمەنی 20 و 70 نیشان دەدەن: && بۆ 20 true و بۆ 70 false دەدات؛ || بۆ 70 true دەدات.
&&: both must be true. ||: one is enough.&&: دەبێت هەردووکیان ڕاست بن. ⁦||⁩: یەکێکیان بەسە.CêIT

Comparisons are worked out before && and ||, so age >= 18 && age <= 65 needs no brackets. Python writes the same operators as words: and, or, not (Combining conditions).

بەراوردەکان پێش && و || دەژمێردرێن، بۆیە age >= 18 && age <= 65 پێویستی بە کەوانە نییە. Python هەمان بە وشە دەنووسێت: and، or، not (بەستنی مەرجەکان).

Two conditions at once: &&, || and !دوو مەرج پێکەوە: &&، ⁦||⁩ و !

Only booleans, never numbersتەنیا بوولیان، هەرگیز ژمارە نا

In C, a number can be a condition: zero means false and any other number true, and some tables describe && in those words. Java is stricter: the operands of &&, || and ! must be booleans, and numbers are a compile error:

لە Cـدا ژمارە دەتوانێت بێت: سفر واتە هەڵە و هەر ژمارەیەکی تر واتە ڕاست، هەندێک خشتەش && بەو شێوەیە وەسف دەکەن. Java توندترە: &&، || و ! دەبێت بن و ژمارە :

LogicalOnInts.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class LogicalOnInts {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        System.out.println(a && b);
    }
}

The maths chain 18 <= age <= 65 fails for the same reason: 18 <= age is a boolean, and a boolean cannot be compared with 65. Write age >= 18 && age <= 65. (Python allows both: Truthiness, Chained comparisons.)

زنجیرەی بیرکاریی 18 <= age <= 65 بە هەمان هۆ سەرناکەوێت: 18 <= age و ناتوانرێت لەگەڵ ⁦65⁩دا بەراورد بکرێت. بنووسە age >= 18 && age <= 65. (Python ڕێگە بە هەردووکیان دەدات: ڕاستیی نرخەکان، بەراوردی زنجیرەیی.)

AgeChain.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class AgeChain {
    public static void main(String[] args) {
        int age = 20;
        System.out.println(18 <= age <= 65);
    }
}

All combinations: truth tablesهەموو حاڵەتەکان: خشتەکانی ڕاستی

Two booleans have four combinations. A lists every one with its result. Java can print its own truth tables; %-7b prints a boolean in seven places, on the left (Width and flags):

دوو چوار حاڵەتیان هەیە. هەموویان لەگەڵ ئەنجامەکانیان ڕیز دەکات. Java دەتوانێت خۆی چاپ بکات؛ %-7b لە حەوت شوێندا، لە لای چەپ، چاپ دەکات (پانی و نیشانەکان):

TruthTables.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class TruthTables {
    public static void main(String[] args) {
        System.out.println("a      b      a && b  a || b");
        System.out.printf("%-7b%-7b%-8b%b%n", false, false, false && false, false || false);
        System.out.printf("%-7b%-7b%-8b%b%n", false, true, false && true, false || true);
        System.out.printf("%-7b%-7b%-8b%b%n", true, false, true && false, true || false);
        System.out.printf("%-7b%-7b%-8b%b%n", true, true, true && true, true || true);
        System.out.println();
        System.out.println("a      !a");
        System.out.printf("%-7b%b%n", false, !false);
        System.out.printf("%-7b%b%n", true, !true);
    }
}
Three truth tables. AND: a && b is true only in the last row, where a and b are both true. OR: a || b is false only in the first row, where both are false. NOT: !a gives true for false and false for true. Note: these are the same tables as the AND, OR and NOT gates; Java takes only boolean operands.سێ خشتەی ڕاستی. AND: a && b تەنیا لە دوایین ڕیزدا ڕاستە، کە a و b هەردووکیان ڕاستن. OR: a || b تەنیا لە یەکەم ڕیزدا هەڵەیە، کە هەردووکیان هەڵەن. NOT: !a بۆ false true و بۆ true false دەدات. تێبینی: ئەمانە هەمان خشتەکانی گەیتی AND، گەیتی OR و گەیتی NOTـن؛ Java تەنیا بوولیان وەک کارپێکراو وەردەگرێت.
Truth tables of &&, || and ! &&، ⁦||⁩ و !CêIT

These are the tables of the logic gates in digital circuits: the AND gate, the OR gate and the NOT gate. Maths writes AND as ∧\land, OR as ∨\lor and NOT as ¬\lnot (The same ideas in code).

ئەمانە خشتەکانی لە سووڕە دیجیتاڵییەکاندا: گەیتی AND، گەیتی OR و گەیتی NOT. بیرکاری AND بە ∧\land، OR بە ∨\lor و NOT بە ¬\lnot دەنووسێت (هەمان بیرۆکەکان لە کۆددا).

Which goes first?کامیان یەکەم؟

! is worked out first, then arithmetic, then comparisons, then &&, and || last of the three (Operator precedence). So true || false && false means true || (false && false):

! یەکەم دەژمێردرێت، پاشان ، پاشان بەراوردەکان، پاشان && و لە کۆتاییدا || (پێشینەیی کارپێکەرەکان). بۆیە true || false && false واتە true || (false && false):

LogicalOrder.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class LogicalOrder {
    public static void main(String[] args) {
        System.out.println(true || false && false);
        System.out.println((true || false) && false);
        System.out.println(!true || true);
        System.out.println(!(true || true));
    }
}
A staircase from first to last: ! (not); arithmetic * / % + -; comparisons < > <= >= == !=; && (and); || (or); ?: (choose); = (store). Below: true || false && false = true || (false && false) = true. Note: && is worked out before ||; brackets make the order clear.پەیژەیەک لە یەکەمەوە بۆ دوایین: ! (NOT)؛ ژمێرەیی * / % + -؛ بەراوردەکان < > <= >= == !=؛ && (AND)؛ || (OR)؛ ?: (هەڵبژاردن)؛ = (دانان). لە خوارەوە: true || false && false = true || (false && false) = true. تێبینی: && پێش || دەژمێردرێت؛ کەوانە ڕیزبەندییەکە ڕوون دەکاتەوە.
Which is worked out first?کامیان یەکەم دەژمێردرێت؟CêIT

Brackets make a mix of && and || easier to read, even when they change nothing: (year % 4 == 0 && year % 100 != 0) || year % 400 == 0.

کەوانە تێکەڵەی && و || ئاسانتر دەکات بۆ خوێندنەوە، تەنانەت کاتێک هیچ ناگۆڕن: (year % 4 == 0 && year % 100 != 0) || year % 400 == 0.

Stop as soon as the answer is knownوەستان هەر کە وەڵامەکە زانرا

&& and || work from left to right and stop as soon as the result is certain. If the left side of && is false, the right side is never evaluated; if the left side of || is true, the right side is skipped. This is , and it lets the left side protect the right side. With d = 0:

&& و || لە چەپەوە بۆ ڕاست کار دەکەن و هەر کە ئەنجامەکە دڵنیا بوو دەوەستن. ئەگەر لای چەپی && هەڵە بێت، لای ڕاست هەرگیز ناژمێردرێت؛ ئەگەر لای چەپی || ڕاست بێت، لای ڕاست تێدەپەڕێنرێت. ئەمە و ڕێگە دەدات لای چەپ لای ڕاست بپارێزێت. کاتێک d = 0:

SafeDivision.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class SafeDivision {
    public static void main(String[] args) {
        int d = 0;
        boolean bigShare = d != 0 && 10 / d > 1;
        System.out.println(bigShare);
    }
}
Animation. d = 0. Java works out the left side, d != 0, which is false. The && gate closes: the right side, 10 / d > 1, is never evaluated, so the result is false and no division by zero happens. Last frame: in the wrong order, 10 / d > 1 && d != 0, the division runs first and the program stops with ArithmeticException: / by zero.
Animation. d = 0. Java works out the left side, d != 0, which is false. The && gate closes: the right side, 10 / d > 1, is never evaluated, so the result is false and no division by zero happens. Last frame: in the wrong order, 10 / d > 1 && d != 0, the division runs first and the program stops with ArithmeticException: / by zero.
&& stops as soon as the answer is known&& هەر کە وەڵامەکە زانرا دەوەستێتCêIT

Put the guard first. In the wrong order the division runs before the check:

پاسەوانەکە بخە پێشەوە. بە ڕیزبەندیی هەڵە، دابەشکردنەکە پێش پشکنینەکە جێبەجێ دەبێت:

UnsafeDivision.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class UnsafeDivision {
    public static void main(String[] args) {
        int d = 0;
        boolean bigShare = 10 / d > 1 && d != 0;
        System.out.println(bigShare);
    }
}

|| guards the same way: people == 0 || bread / people < 2 never divides when there are no people: with people = 0 the left side is already true, so the whole condition is true and the division is skipped.

|| بە هەمان شێوە پاسەوانی دەکات: people == 0 || bread / people < 2 هەرگیز دابەش ناکات کاتێک کەس نییە: بە people = 0 لای چەپ پێشتر ڕاستە، بۆیە هەموو ڕاستە و دابەشکردنەکە تێدەپەڕێنرێت.

Stop as soon as the answer is knownوەستان هەر کە وەڵامەکە زانرا

& and |: no shortcut& و |: بێ کورتبڕ

On booleans, & and | give the same results as && and ||, but they always evaluate both sides. A counter shows the difference: ++checks runs only when its side is evaluated, which is a :

لەسەر ، & و | هەمان ئەنجامی && و || دەدەن، بەڵام هەمیشە هەردوو لا دەژمێرن. جیاوازییەکە پیشان دەدات: ++checks تەنیا کاتێک جێبەجێ دەبێت کە لاکەی دەژمێردرێت، کە ئەمە :

AndVersusAmpersand.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class AndVersusAmpersand {
    public static void main(String[] args) {
        int checks = 0;
        boolean a = (5 > 10) && (++checks > 0);
        System.out.println(a + ", checks = " + checks);
        boolean b = (5 > 10) & (++checks > 0);
        System.out.println(b + ", checks = " + checks);
        boolean c = (5 < 10) || (++checks > 0);
        System.out.println(c + ", checks = " + checks);
        boolean e = (5 < 10) | (++checks > 0);
        System.out.println(e + ", checks = " + checks);
    }
}
Two rows. (5 > 10) && (++checks > 0): the left side is false, the right side is never evaluated and checks stays 0; the program prints false, checks = 0. (5 > 10) & (++checks > 0): the right side is evaluated and checks becomes 1; it prints false, checks = 1. Note: likewise || skips the right side when the left is true, and | never skips.دوو ڕیز. (5 > 10) && (++checks > 0): لای چەپ هەڵەیە، لای ڕاست هەرگیز ناژمێردرێت و checks هەر 0 دەمێنێتەوە؛ بەرنامەکە false, checks = 0 چاپ دەکات. (5 > 10) & (++checks > 0): لای ڕاست دەژمێردرێت و checks دەبێتە 1؛ false, checks = 1 چاپ دەکات. تێبینی: بە هەمان شێوە || کاتێک لای چەپ true بێت لای ڕاست تێدەپەڕێنێت، بەڵام | هەرگیز.
&& may skip the right side; & always works out both&& دەتوانێت لای ڕاست تێپەڕێنێت؛ & هەمیشە هەردووکیان دەژمێرێتCêIT

So & is no guard: d != 0 & 10 / d > 1 still divides by zero and stops with ArithmeticException. Use && and || in conditions; & and | are mainly for bits (AND gate).

کەواتە & پاسەوان نییە: d != 0 & 10 / d > 1 هەر بەسەر سفردا دابەش دەکات و بە ArithmeticException دەوەستێت. لە && و || بەکار بهێنە؛ & و | زیاتر بۆ بیتن (گەیتی AND).

Turning a not around: De Morgan's lawsسەلمێنراوەکانی دی مۆرگان

A ! in front of brackets can be moved inside with : flip each part and swap && and ||. !(a && b) is !a || !b, and !(a || b) is !a && !b. A student must resit when it is not true that the mark is at least 50 and the attendance at least 75. Both forms agreed in all four runs:

!ـێک لە پێش کەوانەوە دەتوانرێت بە ببرێتە ناوەوە: هەر بەشێک پێچەوانە بکەرەوە و && و || ئاڵوگۆڕ بکە. !(a && b) دەبێتە !a || !b و !(a || b) دەبێتە !a && !b. قوتابییەک دەبێت دووپاتە تاقیکردنەوە بکات کاتێک ڕاست نییە کە نمرەکەی لانیکەم ⁦50⁩ و ئامادەبوونی لانیکەم ⁦75⁩ بێت. هەردوو شێوەکە لە هەر چوار جێبەجێکردنەکەدا وەک یەک بوون:

Resit.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class Resit {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Mark and attendance: ");
        int mark = input.nextInt();
        int attendance = input.nextInt();
        boolean resitA = !(mark >= 50 && attendance >= 75);
        boolean resitB = mark < 50 || attendance < 75;     // De Morgan
        System.out.println(resitA + " " + resitB);
    }
}
!(mark >= 50 && attendance >= 75) is turned into mark < 50 || attendance < 75 in three steps: take the ! inside the brackets, flip each comparison, swap && and ||. A table of four runs (80 90, 80 60, 40 90, 40 60) shows both forms giving false, true, true, true. At the bottom, the general laws: !(a && b) == (!a || !b) and !(a || b) == (!a && !b).!(mark >= 50 && attendance >= 75) بە سێ هەنگاو دەکرێت بە mark < 50 || attendance < 75: ! ببە ناو کەوانەکەوە، هەر بەراوردێک پێچەوانە بکەرەوە، && و || ئاڵوگۆڕ بکە. خشتەیەکی چوار جێبەجێکردن (80 90، 80 60، 40 90، 40 60) پیشان دەدات هەردوو شێوەکە false، true، true، true دەدەن. لە خوارەوە یاسا گشتییەکان: !(a && b) == (!a || !b) و !(a || b) == (!a && !b).
De Morgan's laws: move the ! inside: ! ببە ناو کەوانەکەوەCêIT

The second form reads like a sentence: the mark is low, or the attendance is low. Remember that the opposite of >= is <, not <=. The same laws are proved for gates in De Morgan in programs.

شێوەی دووەم وەک ڕستەیەک دەخوێنرێتەوە: نمرەکە کەمە، یان ئامادەبوون کەمە. لەبیرت بێت پێچەوانەی >= <ـە، نەک <=. هەمان یاساکان بۆ گەیتەکان لە دی مۆرگان لە بەرنامەکاندا دەسەلمێنرێن.

An if inside an ififـێک لەناو ifـێکی تردا

An if can stand inside the block of another if: a . There is an outer if and an inner if; the inner one is checked only when the outer condition is true. The inner if can hold another if, with no limit to the depth:

ifـێک دەتوانێت لەناو بلۆکی ifـێکی تردا بێت: . ifـێکی دەرەوە و ifـێکی ناوەوە هەیە؛ ناوەوەکە تەنیا کاتێک دەپشکنرێت کە دەرەوە ڕاست بێت. ifـی ناوەوە دەتوانێت ifـێکی تری تێدا بێت، بێ هیچ سنوورێک بۆ قووڵی:

TEXT
if (condition1) {
    // runs when condition1 is true
    if (condition2) {
        // runs when condition1 and condition2 are true
    }
}
BloodDonor.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class BloodDonor {
    public static void main(String[] args) {
        int age = 20;
        int weight = 80;
        if (age >= 18) {
            if (weight > 50) {
                System.out.println("You are eligible to donate blood");
            }
        }
    }
}
Two checks in a row: the values age = 20 and weight = 80 pass the outer check age >= 18 (true) and then the inner check weight > 50 (true) and reach You are eligible to donate blood. A false at either check leads to the same result: nothing is printed. Note: a simplified classroom rule; real blood-donation rules are set by each blood service.دوو پشکنین بە دوای یەکدا: نرخەکانی age = 20 و weight = 80 پشکنینی دەرەوە (age >= 18، true) و پاشان پشکنینی ناوەوە (weight > 50، true) تێدەپەڕێنن و دەگەنە You are eligible to donate blood. false لە هەر پشکنینێکدا هەمان ئەنجامی دەبێت: هیچ چاپ ناکرێت. تێبینی: یاسایەکی سادەکراوی پۆلە؛ یاسا ڕاستەقینەکانی خوێنبەخشین هەر خزمەتگوزارییەکی خوێن دایدەنێت.
Nested if: the inner check comes only after the outer one says yes: پشکنینی ناوەوە تەنیا دوای ئەوە دێت کە پشکنینی دەرەوە بڵێت بەڵێCêIT

Age 18 and weight over 50 kg is a simplified classroom rule: real blood-donation rules (age, weight, health) are set by each country's blood service.

تەمەنی ⁦18⁩ و کێشی زیاتر لە ⁦50⁩ کیلۆ یاسایەکی سادەکراوی پۆلە: یاسا ڕاستەقینەکانی خوێنبەخشین (تەمەن، کێش، تەندروستی) خزمەتگوزاریی خوێنی هەر وڵاتێک دایدەنێت.

An if inside an ififـێک لەناو ifـێکی تردا

An else at each levelelse لە هەر ئاستێکدا

With an else at both levels the program can say which check failed. Each else belongs to the if directly above it, at the same indentation:

بە elseـێک لە هەردوو ئاستدا دەتوانێت بڵێت کام پشکنین سەرنەکەوت. هەر elseـێک سەر بەو ifـەیە کە ڕاستەوخۆ لە سەرەوەیەتی، لە هەمان :

DonorCheck.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class DonorCheck {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Age: ");
        int age = input.nextInt();
        System.out.print("Weight in kg: ");
        int weight = input.nextInt();
        if (age >= 18) {
            if (weight > 50) {
                System.out.println("You can donate blood.");
            } else {
                System.out.println("Sorry: you must weigh more than 50 kg.");
            }
        } else {
            System.out.println("Sorry: you must be 18 or older.");
        }
    }
}

An if inside an ififـێک لەناو ifـێکی تردا

Test the boundariesسنوورەکان تاقی بکەرەوە

This nested program sorts a whole number into three ranges. A first version printed i is greater than 30 for the input 30, although 30 is not greater than 30: the inner else really means 30 or more. With the messages corrected:

ئەم بە لە سێ مەودادا دادەنێت. وەشانێکی یەکەم بۆ ⁦30⁩ i is greater than 30ـی چاپ دەکرد، هەرچەندە ⁦30⁩ لە ⁦30⁩ گەورەتر نییە: elseـی ناوەوە لە ڕاستیدا واتە ⁦30⁩ یان زیاتر. بە پەیامە چاککراوەکان:

RangeTest.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class RangeTest {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an integer number: ");
        int i = input.nextInt();
        if (i >= 20) {
            if (i < 30)
                System.out.println("i is from 20 to 29");
            else
                System.out.println("i is 30 or more");
        } else
            System.out.println("i is smaller than 20");
    }
}
A number line from 15 to 35 split into three ranges: smaller than 20, from 20 to 29, and 30 or more. The test values 19, 20, 29 and 30 are marked. A note shows the first version's output for 30, i is greater than 30, crossed out: 30 is not greater than 30. Note: mistakes hide at the boundaries, 19 | 20 and 29 | 30.هێڵی ژمارەکان لە 15 تا 35 کە کراوە بە سێ مەودا: بچووکتر لە 20، لە 20 تا 29 و 30 یان زیاتر. نرخەکانی تاقیکردنەوە 19، 20، 29 و 30 نیشانە کراون. تێبینییەک دەرخستەی وەشانی یەکەم بۆ 30 پیشان دەدات، i is greater than 30، کە خەتی بەسەردا هاتووە: 30 لە 30 گەورەتر نییە. تێبینی: هەڵەکان لە سنوورەکاندا خۆیان دەشارنەوە، 19 و 20، 29 و 30.
Test the values on both sides of every limitنرخەکانی هەردوو لای هەر سنوورێک تاقی بکەرەوەCêIT

The first version's run for 30 printed:

جێبەجێکردنی وەشانی یەکەم بۆ ⁦30⁩ ئەمەی چاپ کرد:

Outputدەرئەنجام
$ java RangeTest
Enter an integer number: 30
i is greater than 30

Mistakes like this hide at the boundaries, so test the values on both sides of every limit: here 19 and 20, 29 and 30 (Test with answers you know).

هەڵەی لەم جۆرە لە سنوورەکاندا خۆیان دەشارنەوە، بۆیە نرخەکانی هەردوو لای هەر سنوورێک تاقی بکەرەوە: لێرەدا ⁦19⁩ و ⁦20⁩، ⁦29⁩ و ⁦30⁩ (تاقیکردنەوە بە وەڵامی ناسراو).

An if inside an ififـێک لەناو ifـێکی تردا

Nested if or &&?ڕستەی ifـی ناوەکی یان &&؟

Two nested ifs without any else do the same job as one if with &&. With an else they no longer do: this else belongs to the outer if and runs when i > k is false. Both versions in one program:

دوو ifـی ناوەکی بەبێ هیچ elseـێک هەمان کاری یەک if بە && دەکەن. بە elseـێک ئیتر وا نییە: ئەم elseـە سەر بە ifـی دەرەوەیە و کاتێک i > k هەڵە بێت جێبەجێ دەبێت. هەردوو وەشان لە یەک :

NestedOrAnd.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class NestedOrAnd {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("i, j and k: ");
        int i = input.nextInt();
        int j = input.nextInt();
        int k = input.nextInt();

        System.out.print("Nested: ");
        if (i > k) {
            if (j > k)
                System.out.print("i and j are greater than k");
        } else
            System.out.print("i is less than or equal to k");
        System.out.println();

        System.out.print("With &&: ");
        if (i > k && j > k)
            System.out.print("i and j are greater than k");
        System.out.println();
    }
}
Three inputs for i, j and k. 5 6 1: both versions print i and j are greater than k. 0 6 1: the nested version prints i is less than or equal to k, the && version prints nothing, so they differ. 5 0 1: both print nothing. Note: the else belongs to the outer if, so 0 6 1 prints a message only in the nested version.سێ نێوخستە بۆ i، j و k. 5 6 1: هەردوو وەشان i and j are greater than k چاپ دەکەن. 0 6 1: وەشانە ناوەکییەکە i is less than or equal to k چاپ دەکات و وەشانی && هیچ چاپ ناکات، بۆیە جیاوازن. 5 0 1: هەردووکیان هیچ چاپ ناکەن. تێبینی: elseـەکە سەر بە ifـی دەرەوەیە، بۆیە 0 6 1 تەنیا لە وەشانە ناوەکییەکەدا پەیامێک چاپ دەکات.
Nested if and && agree only when there is no else و && تەنیا کاتێک وەک یەکن کە else نەبێتCêIT

Many options: the else if ladderزۆر هەڵبژاردن: پەیژەی else if

When one value decides among several options, chain else if parts, each an . Java tests the conditions from the top down. As soon as one is true, its statement runs and the rest of the ladder is skipped; if none is true, the final else runs. Write every else if under the first if: indenting each one further, like a staircase, is the same code but harder to read.

کاتێک یەک لە نێوان چەند هەڵبژاردنێکدا بڕیار دەدات، بەشەکانی else if بە دوای یەکدا بنووسە، هەریەکەیان . Java لە سەرەوە بۆ خوارەوە دەپشکنێت. هەر کە یەکێکیان ڕاست بوو، جێبەجێ دەبێت و بەشەکانی تری پەیژەکە تێدەپەڕێنرێن؛ ئەگەر هیچیان ڕاست نەبوو، elseـی کۆتایی جێبەجێ دەبێت. هەموو else ifـێک لە ژێر یەکەم ifـدا بنووسە: بۆشایی زیاتر بۆ هەریەکەیان، وەک پلیکانە، هەمان کۆدە بەڵام خوێندنەوەی قورسترە.

MultiIf.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class MultiIf {
    public static void main(String[] args) {
        int i = 20;
        if (i == 10)
            System.out.println("i is 10");
        else if (i == 15)
            System.out.println("i is 15");
        else if (i == 20)
            System.out.println("i is 20");
        else
            System.out.println("i is not present");
    }
}
Animation. i is 20. The ladder tests i == 10: false, so it goes down; i == 15: false, down again; i == 20: true, so println("i is 20") runs and the terminal shows i is 20. The rest of the ladder, the else too, is skipped.
Animation. i is 20. The ladder tests i == 10: false, so it goes down; i == 15: false, down again; i == 20: true, so println("i is 20") runs and the terminal shows i is 20. The rest of the ladder, the else too, is skipped.
The else-if ladder: the first true test winsپەیژەی else if: یەکەم پشکنینی ڕاست دەیباتەوەCêIT

When every test compares the same value with a fixed value, as here, the switch of the next lesson is often clearer.

کاتێک هەموو پشکنینەکان، وەک لێرە، هەمان لەگەڵ جێگیر بەراورد دەکەن، ڕستەی switchـی وانەی داهاتوو زۆرجار ڕوونترە.

Many options: the else if ladderزۆر هەڵبژاردن: پەیژەی else if

A grade ladderپەیژەی نمرە

A realistic ladder turns a mark from 0 to 100 into a grade, with the common bands 90, 80, 70, 60 and 50 (the pass mark is 50). The first test refuses marks outside 0 to 100 with ||:

پەیژەیەکی واقیعی نمرەیەک لە 0 تا ⁦100⁩ دەکات بە پلەیەک، بە ماوە باوەکانی ⁦90⁩، ⁦80⁩، ⁦70⁩، ⁦60⁩ و ⁦50⁩ (نمرەی دەرچوون ⁦50⁩ـە). یەکەم پشکنین بە || ئەو نمرانە ڕەت دەکاتەوە کە لە دەرەوەی 0 تا ⁦100⁩ن:

Grade.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class Grade {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Mark (0-100): ");
        int mark = input.nextInt();
        if (mark < 0 || mark > 100) {
            System.out.println("Invalid mark");
        } else if (mark >= 90) {
            System.out.println("Excellent");
        } else if (mark >= 80) {
            System.out.println("Very good");
        } else if (mark >= 70) {
            System.out.println("Good");
        } else if (mark >= 60) {
            System.out.println("Fair");
        } else if (mark >= 50) {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }
    }
}
A vertical bar from 0 to 100 split into bands: 90 to 100 Excellent (mark >= 90), 80 to 89 Very good, 70 to 79 Good, 60 to 69 Fair, 50 to 59 Pass, 0 to 49 Fail (else). An arrow at 76 points into the Good band. Marks outside 0 to 100, such as 101 and -5, give Invalid mark. Pass mark: 50.ستوونێک لە 0 تا 100 کە کراوە بە چەند ماوەیەک: 90 تا 100 Excellent (mark >= 90)، 80 تا 89 Very good، 70 تا 79 Good، 60 تا 69 Fair، 50 تا 59 Pass، 0 تا 49 Fail (else). تیرێک لە 76 ئاماژە بە ماوەی Good دەکات. نمرەی دەرەوەی 0 تا 100، وەک 101 و -5، Invalid mark دەدەن. نمرەی دەرچوون: 50.
A grade ladder: the first true test winsپەیژەی نمرە: یەکەم پشکنینی ڕاست دەیباتەوەCêIT

Each test needs only a lower limit: when mark >= 70 is reached, Java already knows the mark is below 80. The Python track builds the same idea (The grade decision).

هەر پشکنینێک تەنیا سنووری خوارەوەی پێویستە: کاتێک دەگاتە mark >= 70، Java پێشتر دەزانێت نمرەکە لە ⁦80⁩ کەمترە. ڕێڕەوی Python هەمان بیرۆکە دروست دەکات (بڕیاری نمرە).

Many options: the else if ladderزۆر هەڵبژاردن: پەیژەی else if

The order of the tests mattersڕیزبەندیی پشکنینەکان گرنگە

Because only the first true test runs, the order decides the answer. Here the tests are upside down:

چونکە تەنیا یەکەم پشکنینی ڕاست جێبەجێ دەبێت، ڕیزبەندییەکە وەڵامەکە دیاری دەکات. لێرەدا پشکنینەکان پێچەوانەن:

GradeWrongOrder.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class GradeWrongOrder {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Mark (0-100): ");
        int mark = input.nextInt();
        if (mark >= 50) {
            System.out.println("Pass");
        } else if (mark >= 70) {
            System.out.println("Good");
        } else if (mark >= 90) {
            System.out.println("Excellent");
        } else {
            System.out.println("Fail");
        }
    }
}

95 passes the first test, mark >= 50, so it never reaches the others: a with no message. With >= tests, start at the highest limit and go down (The order matters).

⁦95⁩ یەکەم پشکنین، mark >= 50، تێدەپەڕێنێت، بۆیە هەرگیز ناگاتە ئەوانی تر: بێ پەیام. بە پشکنینی >=، لە بەرزترین سنوورەوە دەست پێ بکە و دابەزە (ڕیزبەندی گرنگە).

Many options: the else if ladderزۆر هەڵبژاردن: پەیژەی else if

Nested ifs or a ladder?ڕستەکانی ifـی ناوەکی یان پەیژە؟

The same grades can be written with nested ifs: each else holds the next if. The results are the same (95 Excellent, 76 Good, 50 Pass, 49 Fail), but every level moves further right and the code grows to 23 lines. The ladder is the same logic written flat. Use nesting when the inner test is about something else, like the weight after the age.

هەمان پلەکان دەکرێت بە بنووسرێن: هەر elseـێک ifـی داهاتوو لەخۆ دەگرێت. ئەنجامەکان وەک یەکن (⁦95 Excellent⁩، ⁦76 Good⁩، ⁦50 Pass⁩، ⁦49 Fail⁩)، بەڵام هەر ئاستێک زیاتر بەرەو ڕاست دەچێت و کۆدەکە دەگاتە ⁦23⁩ دێڕ. پەیژەکە هەمان لۆجیکە بە ڕێکی نووسراو. ناوەکی بەکار بهێنە کاتێک پشکنینی ناوەوە لەبارەی شتێکی ترە، وەک کێش لە دوای تەمەن.

Two code panels. Left, nested ifs (23 lines): each else holds a new if, so the code moves further right at every level. Right, the else-if ladder (13 lines): every else if starts at the same place. Note: both print the same grades, 95 Excellent, 76 Good, 50 Pass and 49 Fail.دوو پەنەڵی کۆد. لای چەپ، ڕستەکانی ifـی ناوەکی (23 دێڕ): هەر elseـێک ifـێکی نوێ لەخۆ دەگرێت، بۆیە کۆدەکە لە هەر ئاستێکدا زیاتر بەرەو ڕاست دەچێت. لای ڕاست، پەیژەی else if (13 دێڕ): هەموو else ifـێک لە هەمان شوێن دەست پێ دەکات. تێبینی: هەردووکیان هەمان پلەکان چاپ دەکەن، 95 Excellent، 76 Good، 50 Pass و 49 Fail.
The same decision: nested ifs drift right, a ladder stays flatهەمان بڕیار: بەرەو ڕاست دەڕۆن، پەیژە ڕێک دەمێنێتەوەCêIT

Which if owns the else?else هی کام ifـە؟

This code has two ifs and one else. The indentation suggests that the else belongs to the first if, but Java ignores indentation: an else always belongs to the nearest if above it, in the same block, that has no else yet. This is the problem. With i = 1, j = 2 and k = 3:

ئەم کۆدە دوو if و یەک elseـی هەیە. وا نیشان دەدات کە elseـەکە سەر بە یەکەم ifـە، بەڵام Java گوێ بە نادات: else هەمیشە سەر بە نزیکترین ifـە لە سەرووییەوە، لە هەمان بلۆکدا، کە هێشتا elseـی نییە. ئەمە کێشەی . کاتێک i = 1، j = 2 و k = 3:

DanglingElse.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class DanglingElse {
    public static void main(String[] args) {
        int i = 1, j = 2, k = 3;
        if (i > j)
            if (i > k)
                System.out.println("A");
        else
            System.out.println("B");
        System.out.println("end");
    }
}
Two versions with i = 1, j = 2, k = 3. Without braces: an arrow shows that the else on line 4 belongs to the inner if on line 2, whatever the indentation shows; the program prints only end. With braces around the inner if: the else belongs to the outer if on line 1, and the program prints B and end.دوو وەشان کاتێک i = 1، j = 2، k = 3. بێ کەوانە: تیرێک پیشان دەدات کە elseـی دێڕی 4 سەر بە ifـی ناوەوەی دێڕی 2یە، بۆشایی سەرەتای دێڕ هەرچی نیشان بدات؛ بەرنامەکە تەنیا end چاپ دەکات. بە کەوانە بە دەوری ifـی ناوەوەدا: elseـەکە سەر بە ifـی دەرەوەی دێڕی 1ـە و بەرنامەکە B و end چاپ دەکات.
An else belongs to the nearest if that has no elseelse سەر بە نزیکترین ifـە کە elseـی نییەCêIT

i > j (1 > 2) is false, so the whole inner if … else is skipped and only end appears; javac -Xlint:all gives no warning at all. To give the else to the outer if, put braces around the inner if:

i > j ⁦(1 > 2)⁩ هەڵەیە، بۆیە هەموو if … elseـی ناوەوە تێدەپەڕێنرێت و تەنیا end دەردەکەوێت؛ javac -Xlint:all هیچ نادات. بۆ دانی elseـەکە بە ifـی دەرەوە، کەوانە بە دەوری ifـی ناوەوەدا دابنێ:

DanglingFixed.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class DanglingFixed {
    public static void main(String[] args) {
        int i = 1, j = 2, k = 3;
        if (i > j) {
            if (i > k)
                System.out.println("A");
        } else
            System.out.println("B");
        System.out.println("end");
    }
}

Do not repeat code in both branchesهەمان کۆد لە هەردوو لقدا دووپاتە مەکەرەوە

Some buildings have no 13th floor: the lift buttons jump from 12 to 14, so above 12 a button shows one more than the real floor. This program prints the actual floor, but the same println appears in both branches:

هەندێک باڵەخانە نهۆمی ⁦13⁩یان نییە: دوگمەکانی ئاسانسۆرەکە لە ⁦12⁩ەوە بازدەدەن بۆ ⁦14⁩، بۆیە لە سەرووی ⁦12⁩ەوە دوگمەیەک یەک زیاتر لە نهۆمی ڕاستەقینە پیشان دەدات. ئەم نهۆمی ڕاستەقینە چاپ دەکات، بەڵام هەمان println لە هەردوو لقدا هەیە:

ActualFloor.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class ActualFloor {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Floor button: ");
        int floor = input.nextInt();
        int actualFloor;
        if (floor > 13) {
            actualFloor = floor - 1;
            System.out.println("Actual floor: " + actualFloor);
        } else {
            actualFloor = floor;
            System.out.println("Actual floor: " + actualFloor);
        }
    }
}

Code that is the same in every case belongs after the if … else, in one place. Then a change to the message is made once, not twice:

ئەو کۆدەی لە هەموو حاڵەتێکدا وەک یەکە، لە دوای if … else دێت، لە یەک شوێندا. ئەوسا گۆڕینی پەیامەکە یەک جار دەکرێت، نەک دوو جار:

ActualFloor.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class ActualFloor {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Floor button: ");
        int floor = input.nextInt();
        int actualFloor;
        if (floor > 13) {
            actualFloor = floor - 1;
        } else {
            actualFloor = floor;
        }
        System.out.println("Actual floor: " + actualFloor);
    }
}
A lift panel with the buttons 10, 11, 12, 14, 15 and 16: there is no button 13, and button 14 is floor 13. Before: the same System.out.println("Actual floor: " + actualFloor); line in both branches. After: the line appears once, after the if … else, one place to change. Buttons 10 and 20 give the actual floors 10 and 19, and button 14 gives 13, in both versions.پەنەڵێکی ئاسانسۆر بە دوگمەکانی 10، 11، 12، 14، 15 و 16: دوگمەی 13 نییە و دوگمەی 14 نهۆمی 13ـە. پێشتر: هەمان دێڕی System.out.println("Actual floor: " + actualFloor); لە هەردوو لقدا. دوای چاککردن: دێڕەکە یەک جار دێت، لە دوای if … else، یەک شوێن بۆ گۆڕین. دوگمەکانی 10 و 20 نهۆمی ڕاستەقینەی 10 و 19 دەدەن و دوگمەی 14 نهۆمی 13 دەدات، لە هەردوو وەشاندا.
Code that every branch repeats belongs after the if … elseئەو کۆدەی هەموو لقێک دووپاتەی دەکاتەوە، دوای ⁦if … else⁩ دێتCêIT

Choosing a value in one line: ?:هەڵبژاردنی نرخێک لە یەک دێڕدا: ?:

When an if … else only chooses between two values, the conditional operator is shorter: condition ? valueIfTrue : valueIfFalse. It has three operands, so it is also called the . Only the chosen value is worked out, so d != 0 ? 100 / d : 0 is safe:

کاتێک if … elseـێک تەنیا لە نێوان دوو هەڵدەبژێرێت، کورتترە: condition ? valueIfTrue : valueIfFalse. سێ هەیە، بۆیە پێی دەوترێت . تەنیا دەژمێردرێت، بۆیە d != 0 ? 100 / d : 0 سەلامەتە:

Ternary.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Ternary {
    public static void main(String[] args) {
        int mark = 72;
        String result = mark >= 50 ? "Pass" : "Fail";
        System.out.println(result);

        int a = 8, b = 13;
        int larger = a > b ? a : b;
        System.out.println("Larger: " + larger);

        int messages = 1;
        System.out.println("You have " + messages + (messages == 1 ? " message" : " messages"));

        int d = 0;
        int share = d != 0 ? 100 / d : 0;     // 100 / d is not worked out
        System.out.println("Share: " + share);
    }
}
String result = mark >= 50 ? "Pass" : "Fail"; with three coloured parts: the condition mark >= 50, the value if true "Pass" and the value if false "Fail". For mark = 72, result = "Pass". Note: only the chosen value is worked out; the same choice as if (mark >= 50) result = "Pass"; else result = "Fail";String result = mark >= 50 ? "Pass" : "Fail"; بە سێ بەشی ڕەنگاوڕەنگ: مەرجەکە mark >= 50، نرخ ئەگەر true بوو "Pass" و نرخ ئەگەر false بوو "Fail". بۆ mark = 72، result = "Pass". تێبینی: تەنیا نرخە هەڵبژێردراوەکە دەژمێردرێت؛ هەمان هەڵبژاردنی if (mark >= 50) result = "Pass"; else result = "Fail";
The conditional operator: choose one of two values: یەکێک لە دوو هەڵبژێرەCêIT

?: groups from right to left, so n > 0 ? "positive" : n < 0 ? "negative" : "zero" chooses among three (for n = -4 it gives negative); use that only for short choices. ?: is an expression, not a statement: written alone, mark >= 50 ? System.out.println("Pass") : … gives not a statement, as A value nobody uses explains. Python writes a if condition else b (Choosing a value in one line).

?: لە ڕاستەوە بۆ چەپ گرووپ دەبێت، بۆیە n > 0 ? "positive" : n < 0 ? "negative" : "zero" لە نێوان سێدا هەڵدەبژێرێت (بۆ n = -4 negative دەدات)؛ تەنیا بۆ هەڵبژاردنی کورت بەکاری بهێنە. ?: ، نەک : بە تەنیا نووسراو، mark >= 50 ? System.out.println("Pass") : … not a statement دەدات، وەک لە نرخێک کە کەس بەکاری ناهێنێتـدا ڕوون کراوەتەوە. Python دەنووسێت a if condition else b (هەڵبژاردنی نرخ لە یەک دێڕدا).

Common mistakesهەڵە باوەکان

You wroteنووسیتjavac or the run saysjavac یان جێبەجێکردن دەڵێتFixچارەسەر
if (a && b) // intsbad operand types for binary operator '&&'Compare: a != 0 && b != 0بەراورد بکە: a != 0 && b != 0
18 <= age <= 65bad operand types for binary operator '<='age >= 18 && age <= 65
day == 5 || 6bad operand types for binary operator '||'day == 5 || day == 6
!x == 5bad operand type int for unary operator '!'x != 5 or !(x == 5)x != 5 یان !(x == 5)
10 / d > 1 && d != 0ArithmeticException: / by zeroThe guard first: d != 0 && …سەرەتا پاسەوانەکە: d != 0 && …
d != 0 & 10 / d > 1ArithmeticException: / by zero&&, not &&&، نەک &
>= 50 first in a grade ladder>= 50 یەکەم لە پەیژەی نمرەدا95 gives Pass, no message⁦95 Pass⁩ دەدات، بێ پەیامHighest limit first.سەرەتا بەرزترین سنوور.
else under two ifs without braceselse لە ژێر دوو ifـدا بەبێ کەوانەit belongs to the inner ifسەر بە ifـی ناوەوەیەBraces around the inner if.کەوانە بە دەوری ifـی ناوەوەدا.
nested ifs with an else → &&ifـی ناوەکی بە else ← &&a different program جیاوازKeep the nesting, or keep the else.ناوەکییەکە بهێڵەوە، یان elseـەکە.
mark >= 50 ? System.out.println("Pass") : …;not a statementif … else, or print the result of ?:if … else، یان ئەنجامی ?: چاپ بکە

The real messages of four of them: three from javac, the last one at run time:

پەیامە ڕاستەقینەکانی چواریان: سێیان لە javacـەوە و دوایینیان لە کاتی جێبەجێکردندا:

Outputدەرئەنجام
$ javac Weekend.java
Weekend.java:4: error: bad operand types for binary operator '||'
        if (day == 5 || 6) {
                     ^
  first type:  boolean
  second type: int
1 error

$ javac NotFirst.java
NotFirst.java:4: error: bad operand type int for unary operator '!'
        if (!x == 5) {
            ^
1 error

$ javac TernaryStatement.java
TernaryStatement.java:4: error: not a statement
        mark >= 50 ? System.out.println("Pass") : System.out.println("Fail");
                   ^
1 error

$ java AmpersandGuard
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at AmpersandGuard.main(AmpersandGuard.java:4)

Practiceڕاهێنان

Exerciseڕاهێنان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. Read a year and say whether it is a leap year. Test 2024, 1900, 2000 and 2026.

ساڵێک کەبیسەیە ئەگەر بەسەر 4دا دابەش ببێت بەڵام بەسەر ⁦100⁩دا نا، یان ئەگەر بەسەر ⁦400⁩دا دابەش ببێت. ساڵێک بخوێنەوە و بڵێ کەبیسەیە یان نا. ⁦2024⁩، ⁦1900⁩، ⁦2000⁩ و ⁦2026⁩ تاقی بکەرەوە.

Show answerوەڵامەکە پیشان بدە
LeapYear.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class LeapYear {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Year: ");
        int year = input.nextInt();
        boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
        System.out.println(year + (leap ? " is a leap year" : " is not a leap year"));
    }
}

1900 is divisible by 100 but not by 400, so it is not a leap year; 2000 is.

⁦1900⁩ بەسەر ⁦100⁩دا دابەش دەبێت بەڵام بەسەر ⁦400⁩دا نا، بۆیە کەبیسە نییە؛ ⁦2000⁩ کەبیسەیە.

ExerciseڕاهێنانA triangle?سێگۆشەیە؟

Three sides make a triangle only if each pair together is longer than the third side. Read three sides and decide.

سێ لا تەنیا کاتێک سێگۆشەیەک دروست دەکەن کە هەر دوو لایەک پێکەوە لە لای سێیەم درێژتر بن. سێ لا بخوێنەوە و بڕیار بدە.

Show answerوەڵامەکە پیشان بدە
Triangle.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class Triangle {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Three sides: ");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        if (a + b > c && a + c > b && b + c > a) {
            System.out.println("These sides make a triangle.");
        } else {
            System.out.println("No triangle.");
        }
    }
}

1 + 2 is not longer than 3, so 1, 2 and 3 lie on one line (Triangle inequality).

⁦1 + 2⁩ لە 3 درێژتر نییە، بۆیە 1، 2 و 3 لەسەر یەک هێڵ دەکەون (لاسەنگەی سێگۆشەیی).

ExerciseڕاهێنانMuseum ticketsبلیتی مۆزەخانە

Children under 6 enter free; under 18 or 60 and over pay 1,000 dinars; everyone else pays 2,000. Use an else if ladder with ||.

منداڵی خوار 6 ساڵ بێبەرانبەر دەچنە ژوورەوە؛ خوار ⁦18⁩ یان ⁦60⁩ و سەرووتر ⁦1,000⁩ دینار دەدەن؛ هەموو کەسێکی تر ⁦2,000⁩ دەدات. پەیژەیەکی else if بە || بەکار بهێنە.

Show answerوەڵامەکە پیشان بدە
Museum.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class Museum {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Age: ");
        int age = input.nextInt();
        if (age < 6) {
            System.out.println("Free");
        } else if (age < 18 || age >= 60) {
            System.out.println("1,000 dinars");
        } else {
            System.out.println("2,000 dinars");
        }
    }
}

The first test catches the youngest children, so age < 18 in the second test only meets ages 6 to 17.

یەکەم پشکنین بچووکترین منداڵان دەگرێت، بۆیە age < 18 لە پشکنینی دووەمدا تەنیا تەمەنی 6 تا ⁦17⁩ دەبینێت.

ExerciseڕاهێنانFlatten the nestingناوەکییەکە ڕێک بکەرەوە

Rewrite with one if and &&: if (temperature > 20) { if (!raining) { System.out.println("Picnic!"); } }

بە یەک if و && دووپاتە بینووسەوە: if (temperature > 20) { if (!raining) { System.out.println("Picnic!"); } }

Show answerوەڵامەکە پیشان بدە
Picnic.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Picnic {
    public static void main(String[] args) {
        int temperature = 24;
        boolean raining = false;
        if (temperature > 20 && !raining) {
            System.out.println("Picnic!");
        }
    }
}

Neither if has an else, so && keeps the meaning.

هیچ کام لە دوو ifـەکە elseـی نییە، بۆیە && واتاکە دەپارێزێت.

ExerciseڕاهێنانPredict the dangling elseelseـی هەڵواسراو پێشبینی بکە

What does this print?

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

JAVA
int x = 5, y = 1;
if (x > 3)
    if (y > 3)
        System.out.println("both are big");
else
    System.out.println("x is small");
System.out.println("end");
Show answerوەڵامەکە پیشان بدە
PredictElse.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class PredictElse {
    public static void main(String[] args) {
        int x = 5, y = 1;
        if (x > 3)
            if (y > 3)
                System.out.println("both are big");
        else
            System.out.println("x is small");
        System.out.println("end");
    }
}

x > 3 is true, so the inner if (y > 3) is tested; it is false, and the else, which belongs to it, prints x is small, a misleading message.

x > 3 ڕاستە، بۆیە if (y > 3)ـی ناوەوە دەپشکنرێت؛ هەڵەیە و ئەو elseـەی سەر بەوە x is small چاپ دەکات، کە پەیامێکی هەڵخەڵەتێنەرە.

ExerciseڕاهێنانLargest of threeگەورەترینی سێ ژمارە

Read three whole numbers and print the largest, once with two ifs and once with ?:.

سێ بخوێنەوە و گەورەترینیان چاپ بکە، جارێک بە دوو if و جارێک بە ?:.

Show answerوەڵامەکە پیشان بدە
LargestOfThree.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class LargestOfThree {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Three whole numbers: ");
        int a = input.nextInt();
        int b = input.nextInt();
        int c = input.nextInt();
        int largest = a;
        if (b > largest) {
            largest = b;
        }
        if (c > largest) {
            largest = c;
        }
        System.out.println("Largest: " + largest);
        int largest2 = a >= b && a >= c ? a : b >= c ? b : c;
        System.out.println("With ?: " + largest2);
    }
}

Test ties (8 8 3) and the largest in each position. Compare Largest of three.

یەکسانبوون ⁦(8 8 3)⁩ و گەورەترین لە هەر شوێنێکدا تاقی بکەرەوە. بەراوردی بکە بە گەورەترینی سێ ژمارە.

ExerciseڕاهێنانThe ladder as nested ifsپەیژەکە وەک ifـی ناوەکی

Write the grade program with nested ifs instead of else if, and check that it gives the same grades.

نمرە بە لە جیاتی else if بنووسە و دڵنیا بە کە هەمان پلەکان دەدات.

Show answerوەڵامەکە پیشان بدە
GradeNested.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class GradeNested {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Mark (0-100): ");
        int mark = input.nextInt();
        if (mark >= 90) {
            System.out.println("Excellent");
        } else {
            if (mark >= 80) {
                System.out.println("Very good");
            } else {
                if (mark >= 70) {
                    System.out.println("Good");
                } else {
                    if (mark >= 60) {
                        System.out.println("Fair");
                    } else {
                        if (mark >= 50) {
                            System.out.println("Pass");
                        } else {
                            System.out.println("Fail");
                        }
                    }
                }
            }
        }
    }
}

Same results, but 23 lines that drift right: the ladder is easier to read.

هەمان ئەنجام، بەڵام ⁦23⁩ دێڕ کە بەرەو ڕاست دەڕۆن: پەیژەکە ئاسانتر دەخوێنرێتەوە.

Summaryکورتە

  • && is true when both sides are true, || when at least one is, ! flips a boolean. Operands must be booleans.
  • && and || short-circuit: put the guard on the left. & and | always evaluate both sides.
  • De Morgan: !(a && b) is !a || !b; !(a || b) is !a && !b.
  • A nested if asks the inner question only when the outer one is true; && replaces it only without else.
  • An else if ladder: the first true test wins; order the tests, and test the boundaries.
  • An else belongs to the nearest unmatched if; braces decide. ?: chooses one of two values.
  • && ڕاستە کاتێک هەردوو لا ڕاست بن، || کاتێک لانیکەم یەکێکیان، ! پێچەوانە دەکاتەوە. دەبێت بن.
  • && و || کورتبڕن: پاسەوانەکە بخە لای چەپ. & و | هەمیشە هەردوو لا دەژمێرن.
  • دی مۆرگان: !(a && b) دەبێتە !a || !b؛ !(a || b) دەبێتە !a && !b.
  • پرسیاری ناوەوە تەنیا کاتێک دەکات کە دەرەوەکە ڕاست بێت؛ && تەنیا بەبێ else جێگەی دەگرێتەوە.
  • پەیژەی else if: یەکەم پشکنینی ڕاست دەیباتەوە؛ پشکنینەکان ڕیز بکە و سنوورەکان تاقی بکەرەوە.
  • else سەر بە نزیکترین ifـی بێ elseـە؛ کەوانەکان بڕیار دەدەن. ?: یەکێک لە دوو هەڵدەبژێرێت.
Review questionsپرسیارەکانی پێداچوونەوە
Why is d != 0 && 10 / d > 1 safe when d is 0?بۆچی d != 0 && 10 / d > 1 سەلامەتە کاتێک d سفرە؟

The left side is false, so && never evaluates the division.

لای چەپ هەڵەیە، بۆیە && هەرگیز دابەشکردنەکە ناژمێرێت.

What does if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); print for i = 1, j = 2, k = 3?if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); بۆ ⁦i = 1⁩، ⁦j = 2⁩، ⁦k = 3⁩ چی چاپ دەکات؟

Nothing: the else belongs to the inner if, which is never reached.

هیچ: elseـەکە سەر بە ifـی ناوەوەیە، کە هەرگیز پێی ناگات.

Write !(mark >= 50 && attendance >= 75) without the !.!(mark >= 50 && attendance >= 75) بەبێ ! بنووسە.

mark < 50 || attendance < 75.

mark < 50 || attendance < 75.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

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

The switch Statementڕستەی switch

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.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.