In Kotlin, range
provides a powerful tool that represents a consecutive succession of values that can often be used in conjunction with conditionals.
In Kotlin, ranges are created using the ..
operator:
StartingValue..EndingValue
The range will start at the value that appears before ..
and will continue until it reaches the value that appears after ..
.
We can check if values are contained within a specified range with the help of the in
keyword:
var num = 5 if (num in 1..10) { println("This value is between 1 and 10.") }
The in
keyword is used to check if a value exists inside of a collection or range. The program above checks if num
exists within the range of 1
through 10
.
We can also check if a character, or Char
, value appears inside of a range:
var letter = 'c' when (letter) { in 'a'..'m' -> println("Letter is in 1st half of alphabet.") in 'n'..'z' -> println("Letter is in 2nd half of alphabet.") else -> println("Not a valid value") }
Note: Letter ranges are case-sensitive.
Instructions
The Scoville Scale is used to measure the heat, or pungency, of a pepper.
Use if
, else
-if
, and else
expression to determine the pungency of a chili pepper based on the pepper’s Scoville Heat Units(SHU).
If the value of sHU
is between…
0
-699
:
- Set
pungency
to"very mild"
.
700
-2999
:
- Set
pungency
to"mild"
.
3000
-24999
:
- Set
pungency
to"moderate"
.
25000
-69999
:
- Set
pungency
to"high"
.
Else:
- Set
pungency
to"very high"
Use a String template and println()
to output the following statement:
A pepper with [sHU] Scoville Heat Units has a [pungency] pungency.