Comparisons: Greater Than and Less Than
Para além da matemática, também podemos comparar dois valores. Podemos comparar valores utilizando o seguinte:
Maior que >
Menor que <
Maior ou igual a >=
Menor ou igual a <=
Estas operações são importantes porque nos permitem tomar decisões e encontrar respostas no nosso código. Serão utilizadas na próxima secção quando começarmos a programar os loops if e while
No entanto, também podem ser utilizadas em código que não são loops if ou while. Um exemplo é o seguinte:
Neste código, tem a variável y definida como 4. Também tem a variável x definida como 3. Na instrução de impressão, está a comparar as variáveis y e x. Se clicares no botão executar, verás que imprime verdadeiro. Isto acontece porque 4 é maior do que 3. Pode brincar com os números e com o operador de comparação para obter resultados diferentes.
Conditionals
Na vida quotidiana, tomamos decisões com base em diferentes situações. Por exemplo, se tivermos fome, comemos um lanche ou se estivermos cansados, vamos para a cama.
Muitas vezes, no código, queremos que o nosso programa faça algo semelhante e tome decisões diferentes com base em situações diferentes. Podemos fazer isso utilizando instruções condicionais.
Em Java, temos quatro declarações condicionais diferentes:
Declarações If
Instruções Else if
Instruções Else
Instruções Switch
No entanto, vamos analisar as três primeiras.
Primeiro, vamos rever a estrutura de uma condicional. Vamos utilizar as palavras-chave:
if
else if
else
Estas são palavras reservadas que fazem parte da sintaxe
Também veremos parênteses (). São eles que mantêm as condições nas declarações condicionais. Por fim, veremos parênteses { }. Eles são usados para abrir e fechar blocos de código. Abaixo está um exemplo de como as condicionais se parecem quando colocamos tudo junto.
Conditionals: If statement
An if statement works like, If the condition is true then do the following task.
If Condition is True, the code inside the statement will run. If Condition is False, the code inside the statement will not run causing the code to leave the statement.
Vamos ver um exemplo! Neste exemplo, estamos a ver qual é a temperatura para determinar se devemos levar um casaco quando a temperatura é de 20 ºC. O que achas que vai acontecer quando executarmos o código? Pensa primeiro e depois executa o código abaixo
O código imprimirá a mensagem "Não precisa de um casaco". Isto deve-se ao facto de 65 ser superior a 60, o que torna a condição verdadeira. Se o número for inferior a 60, como 40, por exemplo, não será impresso nada porque 40 é inferior a 60.
Conditionals: Else If statement
Else if statements work like the following: If the condition is true, run do the following task. Otherwise, if another condition is true, then do a different task.
If Condition_A is True then the code inside the if statement will run. If Condition_A if False, then it will go to the else if statement. If Condition_B is True, the code inside the else if statement will run. If Condition_B if False, then it will exit the statement and none of the code will run.
Lets look at an example! We will use the temperature example again but this time with an else if statement. In this example we are looking at what the temperature is to determine if we should bring a jacket when the temperature is 35 F. What do you think is going to happen when we run the code? Think about it first then run the code below
The code will print out "You might want to bring a jacket". This is because 35 is NOT greater than 60 which makes the first condition false. Because it is false, the code goes to the else if statement. 35 is less than 60 which makes the else if statement true. Because it is true, the code inside the else if statement will run and "You might want to bring a jacket" gets printed.
Conditionals: else statement
Else statements work like the following: If the condition is true then, do the task. Otherwise do the other task.
If Condition is True, then the code inside the if statement will run. Otherwise, the code inside the else statement will run.
This means if Condition is something other than True, so False, the else statement will run.
Lets look at an example! We will use the temperature example again but this time with an else statement. In this example we are looking at what the temperature is to determine if we should bring a jacket when the temperature is 35 F. What do you think is going to happen when we run the code? Think about it first then run the code below
The code will print out "You might want to bring a jacket". This is because 35 is NOT greater than 60 which makes the first condition false. Because it is false, the code goes to the else and "You might want to bring a jacket" gets printed.
In this exercise you will:
Create an int variable called windSpeed and set it equal to 20
create an if statement that compares windSpeed to 15
If windSpeed is less than 15 print out that it's not too windy to go to the beach
You can use an else or else if statement for this next step!
If windSpeed is greater than 15, then print out it's too windy to go to the beach