From f055b25e21f4f24771e2f38787906c5accf0f01c Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Tue, 4 Aug 2026 21:09:18 +0500 Subject: [PATCH] =?UTF-8?q?feat(80-conditionals):=20=D0=BB=D0=BE=D0=BA?= =?UTF-8?q?=D0=B0=D0=BB=D0=B8=20en/es=20=E2=80=94=20=D0=BF=D0=B5=D1=80?= =?UTF-8?q?=D0=B5=D0=B2=D0=BE=D0=B4=20=D0=BF=D0=BE=D0=B4=20=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D1=8B=D0=B9=20ru?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - en создан для всех 5 уроков модуля + модульный description.en.yml - es пересинхронизирован под новый ru у всех пяти уроков: * 30-if — была только вводная часть: не было ASCII-схемы и секций «Блоки кода», «Использование if внутри метода», «if и логические выражения»; в примере переведено возвращаемое значение "pregunta" * 40-if-else — вместо примера с getTypeOfSentence был другой пример (email), не было ASCII-схемы и секций «Два способа оформить if-else» и «Когда else не нужен» * 50-else-if — не было вводной части с разбором ошибки двух отдельных if и ASCII-схемы; вызовы шли до определения метода; переведены возвращаемые значения "pregunta"/"exclamación" * 60-ternary-operator — не было блока «Было/Стало» с getTypeOfSentence и абзаца про вложенные тернарники; ошибка «se reduce a tres líneas» вместо «до одной строки»; в задании не было финального совета * 80-switch — не было ASCII-схемы и всего раздела про switch-выражение (стрелочный синтаксис), переведены литералы "uno"/"dos", лишние обёртки class App, искажён финальный абзац - заполнены пустые/отсутствующие definitions в es (30-if, 40, 50, 80) Co-Authored-By: Claude Opus 5 (1M context) --- modules/80-conditionals/30-if/en/EXERCISE.md | 16 ++ modules/80-conditionals/30-if/en/README.md | 85 ++++++++++ modules/80-conditionals/30-if/en/data.yml | 6 + modules/80-conditionals/30-if/es/README.md | 81 ++++++++-- modules/80-conditionals/30-if/es/data.yml | 4 +- .../80-conditionals/40-if-else/en/EXERCISE.md | 11 ++ .../80-conditionals/40-if-else/en/README.md | 94 +++++++++++ .../80-conditionals/40-if-else/en/data.yml | 8 + .../80-conditionals/40-if-else/es/README.md | 89 +++++++++-- .../80-conditionals/40-if-else/es/data.yml | 6 + .../80-conditionals/50-else-if/en/EXERCISE.md | 19 +++ .../80-conditionals/50-else-if/en/README.md | 92 +++++++++++ .../80-conditionals/50-else-if/en/data.yml | 6 + .../80-conditionals/50-else-if/es/README.md | 83 +++++++--- .../80-conditionals/50-else-if/es/data.yml | 4 + .../60-ternary-operator/en/EXERCISE.md | 15 ++ .../60-ternary-operator/en/README.md | 63 ++++++++ .../60-ternary-operator/en/data.yml | 8 + .../60-ternary-operator/es/EXERCISE.md | 2 + .../60-ternary-operator/es/README.md | 45 ++++-- .../80-conditionals/80-switch/en/EXERCISE.md | 15 ++ .../80-conditionals/80-switch/en/README.md | 134 ++++++++++++++++ modules/80-conditionals/80-switch/en/data.yml | 8 + .../80-conditionals/80-switch/es/README.md | 150 +++++++++++------- modules/80-conditionals/80-switch/es/data.yml | 7 +- modules/80-conditionals/description.en.yml | 5 + 26 files changed, 940 insertions(+), 116 deletions(-) create mode 100644 modules/80-conditionals/30-if/en/EXERCISE.md create mode 100644 modules/80-conditionals/30-if/en/README.md create mode 100644 modules/80-conditionals/30-if/en/data.yml create mode 100644 modules/80-conditionals/40-if-else/en/EXERCISE.md create mode 100644 modules/80-conditionals/40-if-else/en/README.md create mode 100644 modules/80-conditionals/40-if-else/en/data.yml create mode 100644 modules/80-conditionals/50-else-if/en/EXERCISE.md create mode 100644 modules/80-conditionals/50-else-if/en/README.md create mode 100644 modules/80-conditionals/50-else-if/en/data.yml create mode 100644 modules/80-conditionals/60-ternary-operator/en/EXERCISE.md create mode 100644 modules/80-conditionals/60-ternary-operator/en/README.md create mode 100644 modules/80-conditionals/60-ternary-operator/en/data.yml create mode 100644 modules/80-conditionals/80-switch/en/EXERCISE.md create mode 100644 modules/80-conditionals/80-switch/en/README.md create mode 100644 modules/80-conditionals/80-switch/en/data.yml create mode 100644 modules/80-conditionals/description.en.yml diff --git a/modules/80-conditionals/30-if/en/EXERCISE.md b/modules/80-conditionals/30-if/en/EXERCISE.md new file mode 100644 index 00000000..b1b92b87 --- /dev/null +++ b/modules/80-conditionals/30-if/en/EXERCISE.md @@ -0,0 +1,16 @@ + +Implement the method `getSentenceTone()`, which accepts a string and determines the tone of the sentence. If all the characters are in upper case, then it is a scream — `scream`. Otherwise it is a normal sentence — `normal`. + +Examples of calls: + +```java +App.getSentenceTone("Hello"); // "normal" +App.getSentenceTone("WOW"); // "scream" +``` + +The algorithm: + +1. Generate an upper-case string based on the argument string with the help of `toUpperCase()`. +2. Compare it with the original string: + * If the strings are equal, then the argument string is in upper case + * Otherwise the argument string is not in upper case diff --git a/modules/80-conditionals/30-if/en/README.md b/modules/80-conditionals/30-if/en/README.md new file mode 100644 index 00000000..4191ba58 --- /dev/null +++ b/modules/80-conditionals/30-if/en/README.md @@ -0,0 +1,85 @@ +Logical expressions can check different conditions. But on their own they only return `true` or `false`. So that the program performs different actions depending on the result, Java has the `if` construct. + +```java +if (5 > 3) { + System.out.println("Yes, it is true"); +} +``` + +Here the string `"Yes, it is true"` will be printed, because the condition `5 > 3` is true. + +```text +┌───────────┐ +│ condition │ +└─────┬─────┘ + true │ + ↓ +┌───────────┐ +│ if body │ +└───────────┘ +``` + +After the word `if`, a logical expression is written in parentheses. Then a block of code goes in curly braces. This block will be executed only if the condition is true. If it is false, the block is skipped, and the method continues its work from the next line. + +## Blocks of code + +All the instructions inside the curly braces form one block. They are executed together when the condition is true. + +```java +if (10 == 10) { + System.out.println("First"); + System.out.println("Second"); +} + +System.out.println("Goodbye!"); +``` + +Here `"First"` and `"Second"` will be printed, because the condition was met. And `"Goodbye!"` will be printed in any case, because that line is already outside the block. The principle is the same as in the definition of methods. + +## Using if inside a method + +Let's write a method that determines the type of the sentence passed to it. If the sentence ends with a question mark, the method will return `"question"`; otherwise it will return `"general"`: + +```java +public static String getTypeOfSentence(String sentence) { + if (sentence.endsWith("?")) { + return "question"; + } + + return "general"; +} + +App.getTypeOfSentence("Hodor"); // "general" +App.getTypeOfSentence("Hodor?"); // "question" +``` + +Here two `return` statements work at once. If the condition inside `if` is met, `return "question"` fires and the method ends. If the condition is false, the block is skipped and control passes to the line with `return "general"`. + +The method ends up having several exit points. This is a frequent practice. Depending on the condition, the method finishes in different ways. + +The `getTypeOfSentence` method uses `if`, but it returns strings, so it is not considered a predicate. As a predicate, let's look at a method that checks whether there is enough money for a purchase: + +```java +public static boolean hasEnoughMoney(int balance, int price) { + if (balance >= price) { + return true; + } + + return false; +} + +App.hasEnoughMoney(100, 50); // true +App.hasEnoughMoney(30, 50); // false +``` + +## if and logical expressions + +We wrote the `hasEnoughMoney` method with `if`. But in this form it could do without it, because the result of the comparison is already a logical expression in itself: + +```java +public static boolean hasEnoughMoney(int balance, int price) { + return balance >= price; +} +``` + +In simple cases it is better to return such an expression right away. `if` is needed where additional actions besides returning the result are performed inside the block. The more complex programs become, the more often such situations occur. diff --git a/modules/80-conditionals/30-if/en/data.yml b/modules/80-conditionals/30-if/en/data.yml new file mode 100644 index 00000000..8479d293 --- /dev/null +++ b/modules/80-conditionals/30-if/en/data.yml @@ -0,0 +1,6 @@ +--- +name: The conditional construct (if) +tips: [] +definitions: + - name: The conditional construct + description: 'a way to set a condition for executing code. For example, `if (x > 10) { ... }`' diff --git a/modules/80-conditionals/30-if/es/README.md b/modules/80-conditionals/30-if/es/README.md index ecccf400..83bf8098 100644 --- a/modules/80-conditionals/30-if/es/README.md +++ b/modules/80-conditionals/30-if/es/README.md @@ -1,24 +1,85 @@ -Las estructuras condicionales permiten ejecutar diferentes fragmentos de código basados en comprobaciones lógicas. Veamos un ejemplo típico: +Las expresiones lógicas saben comprobar distintas condiciones. Pero por sí solas únicamente devuelven `true` o `false`. Para que el programa realice acciones distintas según el resultado, en Java existe la construcción `if`. -* Una persona quiere pagar una compra con tarjeta. -* Si hay suficiente dinero en la cuenta, se deducirá automáticamente la cantidad necesaria. -* Si no hay suficiente dinero, la operación será rechazada. +```java +if (5 > 3) { + System.out.println("Yes, it is true"); +} +``` + +Aquí la cadena `"Yes, it is true"` se imprimirá, porque la condición `5 > 3` es verdadera. + +```text +┌───────────┐ +│ condición │ +└─────┬─────┘ + true │ + ↓ +┌───────────┐ +│ cuerpo if │ +└───────────┘ +``` + +Después de la palabra `if`, entre paréntesis, se escribe una expresión lógica. Luego, entre llaves, va un bloque de código. Ese bloque se ejecutará solo si la condición es verdadera. Si es falsa, el bloque se salta y el método sigue trabajando desde la línea siguiente. + +## Bloques de código + +Todas las instrucciones que están dentro de las llaves forman un bloque. Se ejecutan juntas cuando la condición es verdadera. + +```java +if (10 == 10) { + System.out.println("First"); + System.out.println("Second"); +} + +System.out.println("Goodbye!"); +``` + +Aquí se imprimirán `"First"` y `"Second"`, porque la condición se cumplió. Y `"Goodbye!"` se imprimirá en cualquier caso, porque esa línea está ya fuera del bloque. El principio es el mismo que en la definición de métodos. + +## El uso de if dentro de un método -Para el ejemplo, escribiremos un método que determina el tipo de una oración dada. Al principio, distinguirá entre oraciones normales e interrogativas: +Escribamos un método que determina el tipo de la oración que se le pasa. Si la oración termina con un signo de interrogación, el método devolverá `"question"`; en caso contrario devolverá `"general"`: ```java public static String getTypeOfSentence(String sentence) { if (sentence.endsWith("?")) { - return "pregunta"; + return "question"; } return "general"; } -App.getTypeOfSentence("Hola"); // "general" -App.getTypeOfSentence("¿Hola?"); // "pregunta" +App.getTypeOfSentence("Hodor"); // "general" +App.getTypeOfSentence("Hodor?"); // "question" ``` -`if` es una construcción del lenguaje que controla el orden de las instrucciones. Se le pasa una expresión lógica entre paréntesis y luego se describe un bloque de código entre llaves. Este bloque de código se ejecutará solo si la condición se cumple. +Aquí funcionan a la vez dos `return`. Si la condición dentro de `if` se cumple, se ejecuta `return "question"` y el método termina. Si la condición es falsa, el bloque se salta y el control pasa a la línea con `return "general"`. + +El método acaba teniendo varios puntos de salida. Es una práctica frecuente. Según la condición, el método termina de una manera o de otra. + +El método `getTypeOfSentence` usa `if`, pero devuelve cadenas, por eso no se considera un predicado. Como predicado veamos un método que comprueba si hay dinero suficiente para una compra: + +```java +public static boolean hasEnoughMoney(int balance, int price) { + if (balance >= price) { + return true; + } + + return false; +} + +App.hasEnoughMoney(100, 50); // true +App.hasEnoughMoney(30, 50); // false +``` + +## if y las expresiones lógicas + +El método `hasEnoughMoney` lo escribimos con `if`. Pero tal como está podría prescindir de él, porque el resultado de la comparación ya es de por sí una expresión lógica: + +```java +public static boolean hasEnoughMoney(int balance, int price) { + return balance >= price; +} +``` -Si la condición no se cumple, se omitirá el bloque de código entre llaves y el método continuará su ejecución. En nuestro caso, la siguiente línea de código, `return "general";`, hará que el método devuelva una cadena y finalice. +En los casos simples es mejor devolver esa expresión directamente. `if` se necesita allí donde dentro del bloque se realizan acciones adicionales además de devolver el resultado. Cuanto más complejos se vuelven los programas, más a menudo aparecen esas situaciones. diff --git a/modules/80-conditionals/30-if/es/data.yml b/modules/80-conditionals/30-if/es/data.yml index 760124bc..d587f89e 100644 --- a/modules/80-conditionals/30-if/es/data.yml +++ b/modules/80-conditionals/30-if/es/data.yml @@ -1,4 +1,6 @@ --- name: Estructura condicional (if) tips: [] -definitions: [] +definitions: + - name: Estructura condicional + description: 'forma de indicar una condición para ejecutar código. Por ejemplo, `if (x > 10) { ... }`' diff --git a/modules/80-conditionals/40-if-else/en/EXERCISE.md b/modules/80-conditionals/40-if-else/en/EXERCISE.md new file mode 100644 index 00000000..92e3e027 --- /dev/null +++ b/modules/80-conditionals/40-if-else/en/EXERCISE.md @@ -0,0 +1,11 @@ + +Implement the method `normalizeUrl()`, which performs the so-called normalization of data. It accepts the address of a site and returns it with *https://* at the beginning. + +The method accepts addresses in the form *ADDRESS* or *https://ADDRESS*, but always returns the address in the form *https://ADDRESS* + +You can use the `startsWith()` method to check whether the string starts with the prefix *https://*. And then, based on that, add or not add *https://*. + +```java +App.normalizeUrl("google.com"); // "https://google.com" +App.normalizeUrl("https://ai.fi"); // "https://ai.fi" +``` diff --git a/modules/80-conditionals/40-if-else/en/README.md b/modules/80-conditionals/40-if-else/en/README.md new file mode 100644 index 00000000..6e67746f --- /dev/null +++ b/modules/80-conditionals/40-if-else/en/README.md @@ -0,0 +1,94 @@ +The `if` construct can check a condition and execute a block of code when it is true. It has a continuation. The `else` branch sets the block that will be executed if the condition in `if` turned out to be false: + +```java +if (x > 5) { + // Will be executed if the condition is true +} else { + // Will be executed if the condition is false +} +``` + +Look at the method below. It determines the type of a sentence by its last character. If the sentence ends with a question mark, the method will return `Sentence is question`; otherwise it will return `Sentence is general`: + +```java +public static String getTypeOfSentence(String sentence) { + String sentenceType; + + if (sentence.endsWith("?")) { + sentenceType = "question"; + } else { + sentenceType = "general"; + } + + return "Sentence is " + sentenceType; +} + +App.getTypeOfSentence("Hodor"); // "Sentence is general" +App.getTypeOfSentence("Hodor?"); // "Sentence is question" +``` + +We added `else` and a new block. It will be executed if the condition in `if` turns out to be false. The word `else` translates as "otherwise". + +```text + ┌───────────┐ + │ condition │ + └─────┬─────┘ + true │ │ false + ↓ ↓ +┌──────────┐ ┌──────────┐ +│ if body │ │ else body│ +└──────────┘ └──────────┘ +``` + +Other `if` conditions can be nested inside the `else` block: + +```java +int number = 10; + +if (number > 10) { + System.out.println("Number is greater than 10"); +} else { + if (number == 10) { + System.out.println("Number is exactly 10"); + } else { + System.out.println("Number is less than 10"); + } +} +``` + +## Two ways of arranging if-else + +The `if-else` construct can be written in two ways. With the help of negation the order of the blocks changes: + +```java +public static String getTypeOfSentence(String sentence) { + String sentenceType; + + if (!sentence.endsWith("?")) { + sentenceType = "general"; + } else { + sentenceType = "question"; + } + + return "Sentence is " + sentenceType; +} +``` + +To make the construct more convenient to arrange, choose the check without negations and adjust the contents of the blocks to it. + +## When else is not needed + +If the `if` branch contains a `return`, then `else` can be omitted. After `return` the method ends, and the next line will be executed only when the condition in `if` turned out to be false: + +```java +public static String getTypeOfSentence(String sentence) { + if (sentence.endsWith("?")) { + return "question"; + } + + // We get here only if the condition above is false + return "general"; +} +``` + +Such a style removes unnecessary nesting. The simpler a method looks, the easier it is to read its logic. diff --git a/modules/80-conditionals/40-if-else/en/data.yml b/modules/80-conditionals/40-if-else/en/data.yml new file mode 100644 index 00000000..ce6a3374 --- /dev/null +++ b/modules/80-conditionals/40-if-else/en/data.yml @@ -0,0 +1,8 @@ +--- +name: The if-else construct +tips: [] +definitions: + - name: else + description: >- + a way to set the block of code that will be executed if the condition with + `if` was not met. diff --git a/modules/80-conditionals/40-if-else/es/README.md b/modules/80-conditionals/40-if-else/es/README.md index 2de53335..d95c8b2f 100644 --- a/modules/80-conditionals/40-if-else/es/README.md +++ b/modules/80-conditionals/40-if-else/es/README.md @@ -1,33 +1,94 @@ -La estructura condicional `if` tiene varias variantes. Una variante incluye un bloque que se ejecuta si la condición es falsa: +La construcción `if` sabe comprobar una condición y ejecutar un bloque de código cuando es verdadera. Tiene una continuación. La rama `else` marca el bloque que se ejecutará si la condición del `if` resultó falsa: ```java if (x > 5) { - // Si la condición es verdadera + // Se ejecutará si la condición es true } else { - // Si la condición es falsa + // Se ejecutará si la condición es false } ``` -Esta estructura puede ser útil para la inicialización de valores. En el siguiente ejemplo, se verifica la existencia de un `email`. Si está ausente, se establece un valor predeterminado; si se proporciona, se realiza una normalización: +Mira el método de abajo. Determina el tipo de la oración por su último carácter. Si la oración termina con un signo de interrogación, el método devolverá `Sentence is question`; en caso contrario devolverá `Sentence is general`: ```java -// Aquí viene el email +public static String getTypeOfSentence(String sentence) { + String sentenceType; -if (email.equals("")) { // Si el email está vacío, establecer el valor predeterminado - email = "support@hexlet.io"; -} else { // De lo contrario, realizar la normalización - email = email.trim().toLowerCase(); + if (sentence.endsWith("?")) { + sentenceType = "question"; + } else { + sentenceType = "general"; + } + + return "Sentence is " + sentenceType; } -// Aquí se utiliza este correo electrónico +App.getTypeOfSentence("Hodor"); // "Sentence is general" +App.getTypeOfSentence("Hodor?"); // "Sentence is question" +``` + +Hemos añadido `else` y un bloque nuevo. Se ejecutará si la condición del `if` resulta falsa. La palabra `else` se traduce como "si no". + +```text + ┌───────────┐ + │ condición │ + └─────┬─────┘ + true │ │ false + ↓ ↓ +┌──────────┐ ┌──────────┐ +│ rama if │ │ rama else│ +└──────────┘ └──────────┘ +``` + +Dentro del bloque `else` se pueden anidar otras condiciones `if`: + +```java +int number = 10; + +if (number > 10) { + System.out.println("Number is greater than 10"); +} else { + if (number == 10) { + System.out.println("Number is exactly 10"); + } else { + System.out.println("Number is less than 10"); + } +} ``` -Si la rama `if` contiene un `return`, entonces el `else` no es necesario, se puede omitir simplemente: +## Dos maneras de plantear un if-else + +La construcción `if-else` se puede escribir de dos maneras. Con la ayuda de la negación cambia el orden de los bloques: ```java -if (/* condición */) { - return /* algún valor */; +public static String getTypeOfSentence(String sentence) { + String sentenceType; + + if (!sentence.endsWith("?")) { + sentenceType = "general"; + } else { + sentenceType = "question"; + } + + return "Sentence is " + sentenceType; } +``` + +Para que la construcción resulte más cómoda de plantear, elige la comprobación sin negaciones y ajusta a ella el contenido de los bloques. + +## Cuando el else no hace falta -// Continuar haciendo algo, porque no se necesita el else +Si la rama `if` contiene un `return`, el `else` se puede omitir. Después de `return` el método termina, y la línea siguiente se ejecutará solo cuando la condición del `if` haya resultado falsa: + +```java +public static String getTypeOfSentence(String sentence) { + if (sentence.endsWith("?")) { + return "question"; + } + + // Llegamos aquí solo si la condición de arriba es falsa + return "general"; +} ``` + +Ese estilo elimina la anidación innecesaria. Cuanto más simple se ve un método, más fácil es leer su lógica. diff --git a/modules/80-conditionals/40-if-else/es/data.yml b/modules/80-conditionals/40-if-else/es/data.yml index a23d9ccd..fc60d2f9 100644 --- a/modules/80-conditionals/40-if-else/es/data.yml +++ b/modules/80-conditionals/40-if-else/es/data.yml @@ -1,2 +1,8 @@ --- name: Estructura if-else +tips: [] +definitions: + - name: else + description: >- + forma de indicar el bloque de código que se ejecutará si la condición del + `if` no se cumple. diff --git a/modules/80-conditionals/50-else-if/en/EXERCISE.md b/modules/80-conditionals/50-else-if/en/EXERCISE.md new file mode 100644 index 00000000..b3ae1bfc --- /dev/null +++ b/modules/80-conditionals/50-else-if/en/EXERCISE.md @@ -0,0 +1,19 @@ + +On the electronic map of Westeros that Sam implemented, the allies of the Starks are shown with a green circle, the enemies with a red one, and the neutral families with a gray one. + +Write a method `whoIsThisHouseToStarks()` for Sam, which accepts the name of a family and returns one of three values: `"friend"`, `"enemy"`, `"neutral"`. + +The rules for determining it: + + * Friends (`"friend"`): "Karstark", "Tally" + * Enemies (`"enemy"`): "Lannister", "Frey" + * Any other families are considered neutral + +Examples of calls: + +```java +App.whoIsThisHouseToStarks("Karstark"); // "friend" +App.whoIsThisHouseToStarks("Frey"); // "enemy" +App.whoIsThisHouseToStarks("Joar"); // "neutral" +App.whoIsThisHouseToStarks("Ivanov"); // "neutral" +``` diff --git a/modules/80-conditionals/50-else-if/en/README.md b/modules/80-conditionals/50-else-if/en/README.md new file mode 100644 index 00000000..518da557 --- /dev/null +++ b/modules/80-conditionals/50-else-if/en/README.md @@ -0,0 +1,92 @@ +The `getTypeOfSentence` method distinguishes only between question sentences and ordinary ones. Let's add support for exclamatory sentences to it. We will do it first through two separate `if` checks: + +```java +public static String getTypeOfSentence(String sentence) { + String sentenceType = ""; + + if (sentence.endsWith("?")) { + sentenceType = "question"; + } + + if (sentence.endsWith("!")) { + sentenceType = "exclamation"; + } else { + sentenceType = "general"; + } + + return "Sentence is " + sentenceType; +} + +App.getTypeOfSentence("Who?"); // "Sentence is general" +App.getTypeOfSentence("No"); // "Sentence is general" +App.getTypeOfSentence("No!"); // "Sentence is exclamation" +``` + +Technically this code works, but it interprets question sentences incorrectly. There is also a problem with the semantics. The presence of an exclamation mark is checked in any case, even when a question mark has already been found. The `else` branch belongs to the second condition, but not to the first. That is why a question sentence gets the type `"general"`. + +To line the checks up into a single chain, the `if` construct supports the `else if` branch. Such a variant fits when there are many checks and they exclude each other: + +```java +if (/* something */) { + +} else if (/* another check */) { + +} else if (/* another check */) { + +} else { + +} +``` + +Pay attention to two things here: + +- The `else` branch may be absent +- The number of `else if` branches can be any + +Let's rewrite the method with `else if`: + +```java +public static String getTypeOfSentence(String sentence) { + String sentenceType; + + if (sentence.endsWith("?")) { + sentenceType = "question"; + } else if (sentence.endsWith("!")) { + sentenceType = "exclamation"; + } else { + sentenceType = "general"; + } + + return "Sentence is " + sentenceType; +} + +App.getTypeOfSentence("Who?"); // "Sentence is question" +App.getTypeOfSentence("No"); // "Sentence is general" +App.getTypeOfSentence("No!"); // "Sentence is exclamation" +``` + +Now all the conditions are lined up into a single construct. The `else if` operator means "if the previous condition was not met, but the current one is". + +```text + ┌─────────────────┐ + │ condition 1 │ + └────┬────────┬───┘ + true │ │ false + ↓ ↓ +┌──────────┐ ┌─────────────────┐ +│ if body │ │ condition 2 │ +└──────────┘ └────┬────────┬───┘ + true │ │ false + ↓ ↓ + ┌───────────┐ ┌──────────┐ + │else if body│ │ else body│ + └───────────┘ └──────────┘ +``` + +The logic of the method is arranged like this: + +- If the last character is `?`, then the type is `"question"` +- Otherwise, if the last character is `!`, then the type is `"exclamation"` +- Otherwise the type is `"general"` + +In the end only one of the blocks belonging to the whole `if` construct will be executed. diff --git a/modules/80-conditionals/50-else-if/en/data.yml b/modules/80-conditionals/50-else-if/en/data.yml new file mode 100644 index 00000000..acdea10c --- /dev/null +++ b/modules/80-conditionals/50-else-if/en/data.yml @@ -0,0 +1,6 @@ +--- +name: The else if construct +tips: [] +definitions: + - name: else if + description: a way to set several alternative conditions. diff --git a/modules/80-conditionals/50-else-if/es/README.md b/modules/80-conditionals/50-else-if/es/README.md index 136290ed..a318b77b 100644 --- a/modules/80-conditionals/50-else-if/es/README.md +++ b/modules/80-conditionals/50-else-if/es/README.md @@ -1,4 +1,30 @@ -En su versión más completa, la estructura `if` no solo contiene la rama `else`, sino también otras comprobaciones condicionales utilizando `else if`. Esta variante se utiliza cuando hay muchas comprobaciones que se excluyen mutuamente: +El método `getTypeOfSentence` distingue solo entre oraciones interrogativas y normales. Vamos a añadirle el soporte de las oraciones exclamativas. Lo haremos primero con dos comprobaciones `if` separadas: + +```java +public static String getTypeOfSentence(String sentence) { + String sentenceType = ""; + + if (sentence.endsWith("?")) { + sentenceType = "question"; + } + + if (sentence.endsWith("!")) { + sentenceType = "exclamation"; + } else { + sentenceType = "general"; + } + + return "Sentence is " + sentenceType; +} + +App.getTypeOfSentence("Who?"); // "Sentence is general" +App.getTypeOfSentence("No"); // "Sentence is general" +App.getTypeOfSentence("No!"); // "Sentence is exclamation" +``` + +Técnicamente este código funciona, pero interpreta mal las oraciones interrogativas. También hay un problema de semántica. La presencia del signo de exclamación se comprueba en cualquier caso, incluso cuando ya se ha encontrado un signo de interrogación. La rama `else` pertenece a la segunda condición, pero no a la primera. Por eso la oración interrogativa recibe el tipo `"general"`. + +Para poner las comprobaciones en una única cadena, la construcción `if` admite la rama `else if`. Esa variante sirve cuando hay muchas comprobaciones y se excluyen mutuamente: ```java if (/* algo */) { @@ -12,38 +38,55 @@ if (/* algo */) { } ``` -Aquí hay dos puntos a tener en cuenta: +Aquí fíjate en dos cosas: -* La rama `else` puede estar ausente. -* El número de condiciones `else if` puede ser cualquier cantidad. +- La rama `else` puede estar ausente +- La cantidad de ramas `else if` puede ser cualquiera -Escribamos un método extendido como ejemplo para determinar el tipo de oración. Reconoce tres tipos de oraciones: +Reescribamos el método con `else if`: ```java -App.getTypeOfSentence("¿Quién?"); // "La oración es una pregunta" -App.getTypeOfSentence("No"); // "La oración es general" -App.getTypeOfSentence("¡No!"); // "La oración es una exclamación" - -public static String getTypeOfSentence(String sentence) -{ - var sentenceType = ""; +public static String getTypeOfSentence(String sentence) { + String sentenceType; if (sentence.endsWith("?")) { - sentenceType = "pregunta"; + sentenceType = "question"; } else if (sentence.endsWith("!")) { - sentenceType = "exclamación"; + sentenceType = "exclamation"; } else { sentenceType = "general"; } - return "La oración es " + sentenceType; + return "Sentence is " + sentenceType; } + +App.getTypeOfSentence("Who?"); // "Sentence is question" +App.getTypeOfSentence("No"); // "Sentence is general" +App.getTypeOfSentence("No!"); // "Sentence is exclamation" +``` + +Ahora todas las condiciones están puestas en una única construcción. El operador `else if` significa "si no se cumple la condición anterior, pero sí se cumple la actual". + +```text + ┌─────────────────┐ + │ condición 1 │ + └────┬────────┬───┘ + true │ │ false + ↓ ↓ +┌──────────┐ ┌─────────────────┐ +│ rama if │ │ condición 2 │ +└──────────┘ └────┬────────┬───┘ + true │ │ false + ↓ ↓ + ┌───────────┐ ┌──────────┐ + │rama else if│ │ rama else│ + └───────────┘ └──────────┘ ``` -Ahora todas las condiciones están organizadas en una única estructura. El operador `else if` significa "si la condición anterior no se cumple, pero la condición actual sí se cumple". La estructura es la siguiente: +La lógica del método está montada así: -- Si el último carácter es `?`, entonces "pregunta" -- De lo contrario, si el último carácter es `!`, entonces "exclamación" -- De lo contrario, "general" +- Si el último carácter es `?`, entonces el tipo es `"question"` +- Si no, si el último carácter es `!`, entonces el tipo es `"exclamation"` +- Si no, el tipo es `"general"` -En consecuencia, solo se ejecutará uno de los bloques de código relacionados con toda la estructura `if`. +Al final se ejecutará solo uno de los bloques que pertenecen a toda la construcción `if`. diff --git a/modules/80-conditionals/50-else-if/es/data.yml b/modules/80-conditionals/50-else-if/es/data.yml index 7e8a6584..c2efda36 100644 --- a/modules/80-conditionals/50-else-if/es/data.yml +++ b/modules/80-conditionals/50-else-if/es/data.yml @@ -1,2 +1,6 @@ --- name: Estructura else if +tips: [] +definitions: + - name: else if + description: forma de indicar varias condiciones alternativas. diff --git a/modules/80-conditionals/60-ternary-operator/en/EXERCISE.md b/modules/80-conditionals/60-ternary-operator/en/EXERCISE.md new file mode 100644 index 00000000..c2c166a1 --- /dev/null +++ b/modules/80-conditionals/60-ternary-operator/en/EXERCISE.md @@ -0,0 +1,15 @@ + +Implement the method `convertString()`, which accepts a string and, if the first letter is not capital, returns the reversed variant of the original string. If the first letter is capital, then the string is returned unchanged. If an empty string is passed in, the method must return an empty string. + +```java +App.convertString("Hello"); // "Hello" +App.convertString("hello"); // "olleh" + +// Do not forget to take the empty string into account! +App.convertString(""); // "" +``` + +* `StringUtils.reverse()` – reversing a string +* `Character.isUpperCase()` – checking a character for upper case + +Try to write two variants of the method: with an ordinary if-else, and with the ternary operator. diff --git a/modules/80-conditionals/60-ternary-operator/en/README.md b/modules/80-conditionals/60-ternary-operator/en/README.md new file mode 100644 index 00000000..2964e612 --- /dev/null +++ b/modules/80-conditionals/60-ternary-operator/en/README.md @@ -0,0 +1,63 @@ +Look at the definition of a method that returns the absolute value of the number passed to it: + +```java +// If it is greater than zero, we give the number itself. If it is less, we remove the sign +public static int abs(int number) { + if (number >= 0) { + return number; + } + + return -number; +} + +App.abs(10); // 10 +App.abs(-10); // 10 +``` + +Java has a construct that is analogous in its action to `if-else`, but at the same time is an expression. It is called the **ternary operator**. + +The ternary operator is the only one of its kind that requires three operands. It helps to write less code for simple conditional expressions. Our example above, with the ternary operator, is reduced to one line: + +```java +public static int abs(int number) { + return number >= 0 ? number : -number; +} +``` + +The general template looks like this: + +```java + ? : +``` + +First a logical expression is written, and then two variants of behavior: + +1. If the condition is true, the variant before the colon is evaluated +2. If the condition is false, the variant after the colon is evaluated + +Let's rewrite the method that determines the type of a sentence with the ternary operator. + +Before: + +```java +public static String getTypeOfSentence(String sentence) { + if (sentence.endsWith("?")) { + return "question"; + } + + return "general"; +} +``` + +After: + +```java +public static String getTypeOfSentence(String sentence) { + return sentence.endsWith("?") ? "question" : "general"; +} + +App.getTypeOfSentence("Hodor"); // "general" +App.getTypeOfSentence("Hodor?"); // "question" +``` + +A ternary operator can be nested inside another ternary operator. But that is considered bad practice — such code is hard to read. diff --git a/modules/80-conditionals/60-ternary-operator/en/data.yml b/modules/80-conditionals/60-ternary-operator/en/data.yml new file mode 100644 index 00000000..ebe015bc --- /dev/null +++ b/modules/80-conditionals/60-ternary-operator/en/data.yml @@ -0,0 +1,8 @@ +--- +name: The ternary operator +tips: [] +definitions: + - name: The ternary operator + description: > + A way to turn a simple conditional instruction into an expression, for + example, `number >= 0 ? number : -number`. diff --git a/modules/80-conditionals/60-ternary-operator/es/EXERCISE.md b/modules/80-conditionals/60-ternary-operator/es/EXERCISE.md index dda8c303..60351d4f 100644 --- a/modules/80-conditionals/60-ternary-operator/es/EXERCISE.md +++ b/modules/80-conditionals/60-ternary-operator/es/EXERCISE.md @@ -11,3 +11,5 @@ App.convertString(""); // "" * `StringUtils.reverse()` – invierte una cadena de texto * `Character.isUpperCase()` – verifica si un carácter está en mayúscula + +Prueba a escribir dos variantes del método: con un if-else normal y con el operador ternario. diff --git a/modules/80-conditionals/60-ternary-operator/es/README.md b/modules/80-conditionals/60-ternary-operator/es/README.md index 4dfcdcdb..e8721615 100644 --- a/modules/80-conditionals/60-ternary-operator/es/README.md +++ b/modules/80-conditionals/60-ternary-operator/es/README.md @@ -1,7 +1,7 @@ -Observa la definición de un método que devuelve el módulo de un número: +Observa la definición de un método que devuelve el valor absoluto del número que se le pasa: ```java -// Si es mayor o igual a cero, devuelve el número. Si es menor, quita el signo +// Si es mayor que cero, damos el propio número. Si es menor, le quitamos el signo public static int abs(int number) { if (number >= 0) { return number; @@ -14,9 +14,9 @@ App.abs(10); // 10 App.abs(-10); // 10 ``` -En Java existe una construcción que es similar a la estructura *if-else*, pero es una expresión. Se llama **operador ternario**. +En Java existe una construcción que por su acción es análoga a `if-else`, pero que además es una expresión. Se llama **operador ternario**. -El operador ternario es único en su tipo, ya que requiere tres operandos. Ayuda a escribir menos código para expresiones condicionales simples. Nuestro ejemplo anterior con el operador ternario se reduce a tres líneas de código: +El operador ternario es el único de su tipo que exige tres operandos. Ayuda a escribir menos código para las expresiones condicionales simples. Nuestro ejemplo de arriba, con el operador ternario, se reduce a una sola línea: ```java public static int abs(int number) { @@ -24,13 +24,40 @@ public static int abs(int number) { } ``` -El patrón general se ve así: +La plantilla general se ve así: ```java - ? : + ? : ``` -Es decir, primero escribimos la expresión lógica y luego dos variantes de comportamiento: +Primero se escribe la expresión lógica, y después dos variantes de comportamiento: -1. Si la condición es verdadera, se ejecuta la variante antes de los dos puntos -2. Si la condición es falsa, se ejecuta la variante después de los dos puntos +1. Si la condición es verdadera, se evalúa la variante que está antes de los dos puntos +2. Si la condición es falsa, se evalúa la variante que está después de los dos puntos + +Reescribamos con el operador ternario el método que determina el tipo de la oración. + +Antes: + +```java +public static String getTypeOfSentence(String sentence) { + if (sentence.endsWith("?")) { + return "question"; + } + + return "general"; +} +``` + +Después: + +```java +public static String getTypeOfSentence(String sentence) { + return sentence.endsWith("?") ? "question" : "general"; +} + +App.getTypeOfSentence("Hodor"); // "general" +App.getTypeOfSentence("Hodor?"); // "question" +``` + +El operador ternario se puede anidar dentro de otro operador ternario. Pero eso se considera una mala práctica: ese código es difícil de leer. diff --git a/modules/80-conditionals/80-switch/en/EXERCISE.md b/modules/80-conditionals/80-switch/en/EXERCISE.md new file mode 100644 index 00000000..d4f49f1d --- /dev/null +++ b/modules/80-conditionals/80-switch/en/EXERCISE.md @@ -0,0 +1,15 @@ + +Implement the method `getNumberExplanation()`, which accepts a number and returns the explanation of this number. If there is no explanation for the number, then `just a number` is returned. Explanations exist only for the following numbers: + + * 666 - devil number + * 42 - answer for everything + * 7 - prime number + +Examples of calls of the function: + +```java +App.getNumberExplanation(8); // just a number +App.getNumberExplanation(666); // devil number +App.getNumberExplanation(42); // answer for everything +App.getNumberExplanation(7); // prime number +``` diff --git a/modules/80-conditionals/80-switch/en/README.md b/modules/80-conditionals/80-switch/en/README.md new file mode 100644 index 00000000..5759d5e1 --- /dev/null +++ b/modules/80-conditionals/80-switch/en/README.md @@ -0,0 +1,134 @@ +Many languages use not only the conditional construct `if`, but also `switch` in addition to it. The `switch` construct is a specialized version of `if`, created for particular situations. + +For example, it is worth using where there is a chain of `if else` with equality checks: + +```java +if (status.equals("processing")) { + // We do the first thing +} else if (status.equals("paid")) { + // We do the second thing +} else if (status.equals("new")) { + // We do the third thing +} else { + // We do the fourth thing +} +``` + +This compound check has a distinctive feature. Every branch here checks the value of the `status` variable. The `switch` construct writes such code shorter and more expressively: + +```java +switch (status) { + case "processing": + // We do the first thing + break; + case "paid": + // We do the second thing + break; + case "new": + // We do the third thing + break; + default: // else + // We do the fourth thing +} +``` + +```text +switch (value) { + │ + ├── case "a" → block 1 + ├── case "b" → block 2 + ├── case "c" → block 3 + └── default → default block +} +``` + +From the point of view of the number of elements, `switch` is quite a complex construct. It includes: + +* The outer description with the `switch` keyword. It has two elements. These are the variable by whose values `switch` chooses the behavior, and the curly braces for the variants of choice +* The `case` and `default` constructs, inside which the behavior for different values of the variable is described. Each `case` corresponds to an `if`, as in the example above. Here `default` is a special situation that corresponds to the `else` branch in conditional constructs. As with `else`, specifying `default` is not required +* The `break` construct, which prevents fall-through. Without it, after the needed `case` the execution will pass to the next `case`. This will continue until the nearest `break` or until the end of the `switch` + +The curly braces in `switch` do not define a block of code, as in other places. Only the syntax shown above is allowed inside. There you can use `case` or `default`. But inside each `case` and `default` the situation is different. Here any arbitrary code is executed: + +```java +switch (count) { + case 1: + // We do something useful + break; + case 2: + // We do something useful + break; + default: + // We do something +} +``` + +## Returning a value from switch + +Sometimes the result obtained inside a `case` finishes the work of the method that contains the `switch`. Then it has to be returned outside somehow. There are two ways to do this. + +The first way creates a variable before the `switch`, fills it in the `case` branches and at the end returns it outside: + +```java +public static String getExplanation(int count) { + // We declare the variable + String result; + + // We fill it + switch (count) { + case 1: + result = "one"; + break; + case 2: + result = "two"; + break; + default: + result = null; + } + + // We return it + return result; +} +``` + +The second way is simpler and shorter. Instead of a variable, you can do an ordinary return from the method inside the `case`. After `return` no code is executed, so `break` is not needed here: + +```java +public static String getExplanation(int count) { + switch (count) { + case 1: + return "one"; + case 2: + return "two"; + default: + return null; + } +} +``` + +## The switch expression + +The classic `switch` has a modern form with arrow syntax. It is called a switch expression and returns the value right away. Every branch is written as `case value -> result;`. Neither `break` nor fall-through between branches is needed here: + +```java +public static String getExplanation(int count) { + return switch (count) { + case 1 -> "one"; + case 2 -> "two"; + default -> null; + }; +} +``` + +One branch handles several values if you list them separated by commas: + +```java +String season = switch (month) { + case 12, 1, 2 -> "winter"; + case 3, 4, 5 -> "spring"; + case 6, 7, 8 -> "summer"; + default -> "autumn"; +}; +``` + +`switch` occurs in code, but technically you can always do without it. The use of this construct is that it expresses the programmer's intention better when specific values of a variable need to be checked. Compared to `else if` blocks, code with `switch` reads more clearly. diff --git a/modules/80-conditionals/80-switch/en/data.yml b/modules/80-conditionals/80-switch/en/data.yml new file mode 100644 index 00000000..4d2c8598 --- /dev/null +++ b/modules/80-conditionals/80-switch/en/data.yml @@ -0,0 +1,8 @@ +--- +name: The Switch construct +tips: [] +definitions: + - name: switch + description: >- + a way to choose the behavior by the value of a variable through `case` + branches, for example, `switch (count) { case 1: ... }`. diff --git a/modules/80-conditionals/80-switch/es/README.md b/modules/80-conditionals/80-switch/es/README.md index ab220983..0215f871 100644 --- a/modules/80-conditionals/80-switch/es/README.md +++ b/modules/80-conditionals/80-switch/es/README.md @@ -1,106 +1,134 @@ -Muchos lenguajes utilizan no solo la estructura condicional `if`, sino también `switch` en adición a ella. La estructura `switch` es una versión especializada de `if`, creada para algunas situaciones particulares. +Muchos lenguajes usan no solo la construcción condicional `if`, sino también `switch` como complemento. La construcción `switch` es una versión especializada de `if`, creada para situaciones particulares. -Por ejemplo, se debe utilizar cuando hay una cadena de `if else` con comprobaciones de igualdad: +Por ejemplo, conviene usarla allí donde hay una cadena de `if else` con comprobaciones de igualdad: ```java if (status.equals("processing")) { - // Hacer algo + // Hacemos lo primero } else if (status.equals("paid")) { - // Hacer algo más + // Hacemos lo segundo } else if (status.equals("new")) { - // Hacer algo más + // Hacemos lo tercero } else { - // Hacer algo más + // Hacemos lo cuarto } ``` -Esta comprobación compuesta tiene una característica distintiva: cada rama aquí es una comprobación del valor de la variable `status`. La estructura `switch` permite escribir este código de forma más corta y expresiva: +Esta comprobación compuesta tiene un rasgo distintivo. Cada rama comprueba aquí el valor de la variable `status`. La construcción `switch` escribe ese código de forma más corta y expresiva: ```java switch (status) { case "processing": - // Hacer algo + // Hacemos lo primero break; case "paid": - // Hacer algo más + // Hacemos lo segundo break; case "new": - // Hacer algo más + // Hacemos lo tercero break; default: // else - // Hacer algo más + // Hacemos lo cuarto } ``` -En términos de cantidad de elementos, `switch` es una estructura bastante compleja. Incluye: +```text +switch (valor) { + │ + ├── case "a" → bloque 1 + ├── case "b" → bloque 2 + ├── case "c" → bloque 3 + └── default → bloque por defecto +} +``` -* Una declaración externa con la palabra clave `switch`. Tiene dos elementos: - - Una variable, cuyos valores serán utilizados por `switch` para seleccionar el comportamiento - - Llaves para los casos de selección -* Las construcciones `case` y `default`, dentro de las cuales se describe el comportamiento para diferentes valores de la variable considerada. Cada `case` corresponde a un `if`, como en el ejemplo anterior. Aquí, `default` es una situación especial que corresponde a la rama `else` en las estructuras condicionales. Al igual que con `else`, no es obligatorio especificar `default`. -* La construcción `break`, que evita la "caída". Si no se especifica, después de ejecutar el `case` necesario, la ejecución pasará al siguiente `case`. Este ciclo se repetirá hasta el `break` más cercano o hasta el final del `switch`. +Desde el punto de vista de la cantidad de elementos, `switch` es una construcción bastante compleja. Incluye: -Las llaves en `switch` no definen un bloque de código, como en otros lugares. Dentro de ellas solo se permite la sintaxis que se muestra arriba, donde se pueden utilizar `case` o `default`. Pero dentro de cada `case` (y `default`) la situación es diferente. Aquí se puede ejecutar cualquier código arbitrario: +* La descripción externa con la palabra clave `switch`. En ella hay dos elementos: la variable por cuyos valores `switch` elige el comportamiento, y las llaves para las variantes de elección +* Las construcciones `case` y `default`, dentro de las cuales se describe el comportamiento para los distintos valores de la variable. Cada `case` corresponde a un `if`, como en el ejemplo de arriba. Aquí `default` es una situación especial que corresponde a la rama `else` de las construcciones condicionales. Igual que con `else`, indicar `default` no es obligatorio +* La construcción `break`, que evita la caída de una rama a otra. Sin ella, después del `case` necesario la ejecución pasará al `case` siguiente. Y así seguirá hasta el `break` más próximo o hasta el final del `switch` + +Las llaves en `switch` no definen un bloque de código, como en otros lugares. Dentro solo se admite la sintaxis que se muestra arriba. Allí se pueden usar `case` o `default`. Pero dentro de cada `case` y `default` la situación es otra. Ahí se ejecuta cualquier código arbitrario: ```java switch (count) { - case 1: - // Hacer algo útil - break; - case 2: - // Hacer algo útil - break; - default: - // Hacer algo + case 1: + // Hacemos algo útil + break; + case 2: + // Hacemos algo útil + break; + default: + // Hacemos algo } ``` -A veces, el resultado obtenido dentro de un `case` es el final de la ejecución del método que contiene el `switch`. En este caso, es necesario devolverlo de alguna manera al exterior. Para resolver esta tarea, hay dos formas. +## La devolución de un valor desde switch + +A veces el resultado obtenido dentro de un `case` termina el trabajo del método que contiene el `switch`. Entonces hay que devolverlo de alguna manera hacia fuera. Para eso hay dos formas. -La primera forma es crear una variable antes del `switch`, llenarla en los `case` y luego devolver el valor de esta variable al exterior: +La primera forma crea una variable antes del `switch`, la rellena en los `case` y al final la devuelve hacia fuera: ```java -class App { - public static String getExplanation(int count) { - // Declarar la variable - String result; - - // Llenarla - switch(count) { - case 1: - result = "uno"; - break; - case 2: - result = "dos"; - break; - default: - result = null; - } - - // Devolverla - return result; +public static String getExplanation(int count) { + // Declaramos la variable + String result; + + // La rellenamos + switch (count) { + case 1: + result = "one"; + break; + case 2: + result = "two"; + break; + default: + result = null; } + + // La devolvemos + return result; } ``` -La segunda forma es más simple y corta. En lugar de crear una variable, se puede utilizar `case`, dentro del cual se puede hacer un retorno normal del método. Después de `return`, no se ejecuta ningún código, por lo que podemos eliminar el `break`: +La segunda forma es más simple y corta. En lugar de una variable, dentro del `case` se puede hacer una devolución normal desde el método. Después de `return` no se ejecuta ningún código, por eso aquí `break` no hace falta: ```java -class App { - public static String getExplanation(int count) { - - switch(count) { - case 1: - return "uno"; - case 2: - return "dos"; - default: - return null; - } +public static String getExplanation(int count) { + switch (count) { + case 1: + return "one"; + case 2: + return "two"; + default: + return null; } } ``` -Aunque `switch` se encuentra en el código, técnicamente siempre se puede prescindir de él. +## La expresión switch + +El `switch` clásico tiene una forma moderna con sintaxis de flecha. Se llama expresión switch y devuelve el valor directamente. Cada rama se escribe como `case valor -> resultado;`. Aquí no hacen falta ni `break` ni la caída entre ramas: + +```java +public static String getExplanation(int count) { + return switch (count) { + case 1 -> "one"; + case 2 -> "two"; + default -> null; + }; +} +``` + +Una sola rama atiende varios valores si se enumeran separados por comas: + +```java +String season = switch (month) { + case 12, 1, 2 -> "winter"; + case 3, 4, 5 -> "spring"; + case 6, 7, 8 -> "summer"; + default -> "autumn"; +}; +``` -La utilidad de esta estructura radica en que expresa mejor la intención del programador cuando se necesita comprobar valores específicos de una variable. A diferencia de los bloques `else if`, el código con `switch` es un poco más largo, pero mucho más fácil de leer. +`switch` aparece en el código, pero técnicamente siempre se puede prescindir de él. La utilidad de esta construcción está en que expresa mejor la intención del programador cuando hay que comprobar valores concretos de una variable. En comparación con los bloques `else if`, el código con `switch` se lee de forma más clara. diff --git a/modules/80-conditionals/80-switch/es/data.yml b/modules/80-conditionals/80-switch/es/data.yml index 16b81dff..6cc2ba50 100644 --- a/modules/80-conditionals/80-switch/es/data.yml +++ b/modules/80-conditionals/80-switch/es/data.yml @@ -1,3 +1,8 @@ --- name: Estructura Switch -definitions: [] +tips: [] +definitions: + - name: switch + description: >- + forma de elegir el comportamiento según el valor de una variable mediante + ramas `case`, por ejemplo, `switch (count) { case 1: ... }`. diff --git a/modules/80-conditionals/description.en.yml b/modules/80-conditionals/description.en.yml new file mode 100644 index 00000000..3d917f4e --- /dev/null +++ b/modules/80-conditionals/description.en.yml @@ -0,0 +1,5 @@ +--- + +name: Conditional constructs +description: | + The task of a predicate function is to get an answer to a question, but usually that is not enough and a certain action has to be performed depending on the answer. If and Switch are Java constructs with the help of which a programmer can choose the needed behavior of the program depending on different conditions: skip some instructions and execute others. That is what we will study in practice in this module.