Um trecho de palestra com um mentor como parte do curso Codegym University. Inscreva-se no curso completo.


"Oi, amigo. Hoje vamos falar sobre declarações if/else ."

"Os programas seriam de pouca utilidade se não respondessem às mudanças das circunstâncias externas. Um programa precisa saber como se adaptar às circunstâncias e executar uma ação em um caso e outras ações em outros casos. Em Java, isso é feito usando o 'instrução if/else' - uma construção especial que torna possível executar diferentes blocos de código se uma condição for satisfeita."

"Consiste em três partes: ' condição ', ' comando 1 ' e ' comando 2 '. Se a condição for verdadeira, então ' comando 1 ' é executado, caso contrário, 'comando 2' é executado. Esses comandos nunca são ambos executados. A declaração é mais ou menos assim:"

Código para uma instrução if/else
if (condition)
    command_1;
else
    command_2;

"Que empolgante! Acho que essa afirmação tornará a programação muito mais interessante!"

"Sim. Aqui estão alguns exemplos para você:"

Código Explicação
1
if (a < b)
    System.out.println("A is less than B");
else
    System.out.println("B is less than  A");
Se a for menor que b, o primeiro comando será executado. Caso contrário, o segundo comando será executado . Os comandos nunca são ambos executados.
2
if (a < b)
{
    System.out.println("A is less than B");
    System.out.println("B is greater than A");
}
else
{
     System.out.println("B is less than A");
     System.out.println("A is greater than B");
}
Você pode substituir um comando por um bloco de código. O resto é o mesmo.
3
if (a < b)
{
    a = 0;
}
else
{
}
Você pode omitir o bloco else se estiver vazio.
Esses três exemplos são totalmente equivalentes.
Você pode omitir as chaves se precisar executar apenas um comando. Se você tiver mais de um comando, precisará manter os colchetes.
4
if (a < b)
{
    a = 0;
}
5
if (a < b)
    a = 0;

"Diego só me pediu para lhe dar algumas tarefas."

2
Tarefa
Java Syntax,  nível 4lição 4
Bloqueado
Good or bad?
Student robot Peter is an overachiever. Previously, his server was configured to receive scores on a five-point scale, but now his teachers have switched to a 12-point scale. But Peter doesn't know this. He's still focused on getting fives. Let's write him a compare method that compares any number with five.
4
Tarefa
Java Syntax,  nível 4lição 4
Bloqueado
Closest to 10
Ten is extremely popular and attractive number. Everyone wants to be a ten. Or at least as close to it as possible. Two numbers are standing around wondering which of them is cooler. Answer: whichever is closer to ten. Let's write these numbers a displayClosestToTen method that will determine which of them is cooler.
4
Tarefa
Java Syntax,  nível 4lição 4
Bloqueado
Come on, lucky seven!
Dice games are popular on the planet Foggy Multidimensions. The rules are different than the Earth version: Multidimensionals perceive far more dimensions than primitive three-dimensional earthlings. Their die has 4294967295 faces. Players win only if they roll a number between 50 and 100. We'll write a method that checks whether the die roll is in this range.
4
Tarefa
Java Syntax,  nível 4lição 4
Bloqueado
Seasons on Terra
An Earth year consists of four seasons, each of which lasts 3 months. While our ship was parked on this cradle of humanity, the Interplanetary Tax Service asked us to write a program to determine the season based on a number corresponding to the month of the year. We don't know why they want it. They say that it's none of our business. But they promised not to remain in our debt.
4
Tarefa
Java Syntax,  nível 4lição 4
Bloqueado
Positive and negative numbers
Diego is tall, but Alfredo is short. Rishi is experienced, but you're a "noob" programmer. Comparisons are unavoidable in life. And the same thing is true in programs. So we'll continue practicing comparisons and displaying stuff on the screen. This time let's compare the entered number with zero and manipulate it based on the result of the comparison.
4
Tarefa
Java Syntax,  nível 4lição 4
Bloqueado
Day of the week
Planet Terra still has "offices"—an outdated type of workspace. With current technology, there is no need for them, but earthlings tend to be nostalgic and haven't been in a hurry to eradicate them. Terrestrial office workers develop "TGIF syndrome": they constantly want to know what day of the week it is. Let's write a program for them!

Um trecho de palestra com um mentor como parte do curso Codegym University. Inscreva-se no curso completo.