Another way to compare two values is with the equality operators.
We can use the equality operator (==
) to check if the value on the right side of the operator is equal to the value on the left. If the values are equivalent the expression will return true
; otherwise, it will return false
:
var userPassword = "secret884" var attemptedPassword = "secret884" if (userPassword == attemptedPassword) { println("The password you entered is correct.") }
This code snippet will output "The password you entered is correct."
because userPassword
and attemptedPassword
have the same value.
On the other hand, the inequality operator (!=
) is used to determine if the values on each side of the !=
operator are different. This expression returns true
when the two values being compared are not equal to each other.
We can use !=
to check if a gathering of 9
people can evenly split 16
slices of pizza amongst themselves:
var slicesOfPizza = 16 var numPeople = 9 if (slicesOfPizza % numPeople != 0) { println("The pizza cannot be split evenly.") } // Prints: The pizza cannot be split evenly.
Using modulo %
, we can find if dividing 16
by 9
has a remainder of 0
. Since the remainder value does not equal 0
, "The pizza cannot be split evenly."
is outputted to the terminal.
Instructions
Create an if
expression that checks if the value of num1
is even.
In the body of the if
expression, use println()
and a String template to output the following:
[num1] is even.
Create a second if
expression that checks if the value of num2
is odd using !=
.
In the body of the if
expression, use println()
and a String template to output the following:
[num2] is odd.