Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions modules/80-conditionals/30-if/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -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`.

Check notice on line 2 in modules/80-conditionals/30-if/en/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/80-conditionals/30-if/en/EXERCISE.md#L2

A comma may be missing after the conjunctive/linking adverb ‘Otherwise’. (SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA[1]) Suggestions: `Otherwise,` URL: https://languagetool.org/insights/post/linking-words/ Rule: https://community.languagetool.org/rule/show/SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA?lang=en-US&subId=1 Category: PUNCTUATION
Raw output
modules/80-conditionals/30-if/en/EXERCISE.md:2:179: A comma may be missing after the conjunctive/linking adverb ‘Otherwise’. (SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA[1])
 Suggestions: `Otherwise,`
 URL: https://languagetool.org/insights/post/linking-words/ 
 Rule: https://community.languagetool.org/rule/show/SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA?lang=en-US&subId=1
 Category: PUNCTUATION

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
85 changes: 85 additions & 0 deletions modules/80-conditionals/30-if/en/README.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions modules/80-conditionals/30-if/en/data.yml
Original file line number Diff line number Diff line change
@@ -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) { ... }`'
81 changes: 71 additions & 10 deletions modules/80-conditionals/30-if/es/README.md
Original file line number Diff line number Diff line change
@@ -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:

Check notice on line 77 in modules/80-conditionals/30-if/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/80-conditionals/30-if/es/README.md#L77

Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1]) Suggestions: `Los Cabos` Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1 Category: MULTITOKEN_SPELLING
Raw output
modules/80-conditionals/30-if/es/README.md:77:115: Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1])
 Suggestions: `Los Cabos`
 Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1
 Category: MULTITOKEN_SPELLING

```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.
4 changes: 3 additions & 1 deletion modules/80-conditionals/30-if/es/data.yml
Original file line number Diff line number Diff line change
@@ -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) { ... }`'
11 changes: 11 additions & 0 deletions modules/80-conditionals/40-if-else/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -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"
```
94 changes: 94 additions & 0 deletions modules/80-conditionals/40-if-else/en/README.md
Original file line number Diff line number Diff line change
@@ -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`:

Check notice on line 11 in modules/80-conditionals/40-if-else/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/80-conditionals/40-if-else/en/README.md#L11

If ‘type’ is a classification term, ‘a’ is not necessary. Use “type of”. (The phrases ‘kind of’ and ‘sort of’ are informal if they mean ‘to some extent’.) (KIND_OF_A[1]) Suggestions: `type of` Rule: https://community.languagetool.org/rule/show/KIND_OF_A?lang=en-US&subId=1 Category: GRAMMAR
Raw output
modules/80-conditionals/40-if-else/en/README.md:11:44: If ‘type’ is a classification term, ‘a’ is not necessary. Use “type of”. (The phrases ‘kind of’ and ‘sort of’ are informal if they mean ‘to some extent’.) (KIND_OF_A[1])
 Suggestions: `type of`
 Rule: https://community.languagetool.org/rule/show/KIND_OF_A?lang=en-US&subId=1
 Category: GRAMMAR

```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.
8 changes: 8 additions & 0 deletions modules/80-conditionals/40-if-else/en/data.yml
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading