Booleans and selection: if/else and logic · Логические переменные и выбор: if/else и логика
Booleans and selection
- A boolean is a value that is either
trueorfalse. - Programs make choices by testing a boolean and running different code.
- In this lesson you learn
if/else if/elseand how to build conditions.
Логические значения и выбор
- Логическое значение — это значение, которое может быть либо
true, либоfalse. - Программы принимают решения, проверяя логическое значение и выполняя разный код.
- В этом уроке вы изучите
if/else if/elseи способы построения условий.
Relational operators
- These compare two values and give a
boolean:<less than,>greater than<=less or equal,>=greater or equal==equal,!=not equal
- Note:
=puts a value into a variable, but==tests if two values are equal.
Операторы сравнения
- Они сравнивают два значения и возвращают
boolean:<меньше,>больше<=меньше или равно,>=больше или равно==равно,!=не равно
- Обратите внимание:
=присваивает значение переменной, но==проверяет, равны ли два значения.
public class Main {
public static void main(String[] args) {
int score = 75;
System.out.println(score > 50); // true
System.out.println(score == 100); // false
System.out.println(score != 75); // false
}
}
if / else if / else
ifruns a block only when its condition istrue.else ifchecks another condition when the ones before werefalse.elseruns when none of the conditions were true.
if / else if / else
ifвыполняет блок только тогда, когда его условие истинно (true).else ifпроверяет другое условие, если предыдущие были ложны (false).elseвыполняется, когда ни одно из условий не было истинным.
public class Main {
public static void main(String[] args) {
int n = -4;
if (n > 0) {
System.out.println("positive");
} else if (n < 0) {
System.out.println("negative");
} else {
System.out.println("zero");
}
}
}
Logical operators
&&means and: true only when both sides are true.||means or: true when at least one side is true.!means not: it flipstruetofalseandfalsetotrue.
Логические операторы
&&означает и: истинно только тогда, когда обе стороны истинны.||означает или: истинно, когда хотя бы одна сторона истинна.!означает не: он меняетtrueнаfalse, аfalseнаtrue.
public class Main {
public static void main(String[] args) {
int age = 16;
boolean teen = age >= 13 && age <= 19;
System.out.println(teen); // true
System.out.println(!teen); // false
System.out.println(age < 13 || age > 19); // false
}
}
Short-circuit
- Java reads
&&and||from left to right and stops early when it can. - With
&&, if the left side isfalse, the answer is alreadyfalse, so the right side is skipped. - With
||, if the left side istrue, the answer is alreadytrue, so the right side is skipped. - This lets you check something is safe before you use it.
Короткое замыкание
- Java читает
&&и||слева направо и прекращает вычисление рано, если это возможно. - При использовании
&&, если левая часть истинна (false), ответ уже известен (false), поэтому правая часть пропускается. - При использовании
||, если левая часть истинна (true), ответ уже известен (true), поэтому правая часть пропускается. - Это позволяет проверить безопасность чего-либо перед использованием.
public class Main {
public static void main(String[] args) {
int x = 0;
// Left side is false, so x / x is never run (no error).
boolean ok = (x != 0) && (10 / x > 1);
System.out.println(ok); // false
}
}
The == vs .equals() String trap
- For
intandboolean,==works fine. - For
String,==checks if they are the same object in memory, not the same letters. - Two Strings with the same letters can still be different objects, so
==may befalse. - Always compare Strings with
.equals(...).
Ловушка строки == против .equals()
- Для
intиboolean,==работает нормально. - Для метода
String,==проверяет, являются ли они одним и тем же объектом в памяти, а не просто одинаковыми буквами. - Две строки с одинаковыми буквами всё равно могут быть разными объектами, поэтому
==может оказатьсяfalse. - Всегда сравнивайте строки с помощью
.equals(...).
public class Main {
public static void main(String[] args) {
String a = "cat";
String b = new String("cat");
System.out.println(a == b); // false (different objects)
System.out.println(a.equals(b)); // true (same letters)
}
}
Common mistakes
- A condition must be a
boolean;if (x = 5)does not compile. - Each
switchcase needs abreak;.
Распространенные ошибки
- Условие должно быть логическим значением (
boolean); использованиеif (x = 5)не скомпилируется. - Для каждого случая
switchтребуетсяbreak;.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
Теперь попробуйте сами
- Каждая задача заранее заполняет каркас класса — напишите свой код внутри main или дополните показанный метод.
- Нажмите Run (Выполнить), чтобы скомпилировать и запустить, затем Check answer (Проверить ответ).
- Ваш код компилируется и выполняется на сервере, поэтому даже первый запуск происходит быстро.
Boolean logic (and/or/not) · Булева логика (and/or/not)
&&, ||, ! combine true/false values — see the truth table. · &&, ||, ! объединяют значения true/false — см. таблицу истинности.
The variable n is -4. Use if / else if / else to print exactly one word: positive if n > 0, negative if n < 0, or zero otherwise. · Переменная n равна -4. Используйте if / else if / else, чтобы напечатать ровно одно слово: positive если n > 0, negative если n < 0 или zero в противном случае.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Complete equal(String a, String b) so it returns true when the two Strings have the same letters. Use .equals, not ==. · Завершите equal(String a, String b) так, чтобы он возвращал true, когда две строки содержат одинаковые буквы. Используйте .equals, а не ==.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Complete inRange(int x) so it returns true when x is between 10 and 20, including both ends (10 and 20 count). Use &&. · Завершите inRange(int x) так, чтобы он возвращал true, когда x находится между 10 и 20, включая оба конца (10 и 20 учитываются). Используйте &&.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.