官术网_书友最值得收藏!

The if expression

The if expression is used to make a logical decision based on the fulfillment of a condition. We make use of the if keyword to write if expressions:

val a = 1

if (a == 1) {
print("a is one")
}

The preceding if expression tests whether the a == 1 (read: a is equal to 1) condition holds true. If the condition is true, the a is one string is printed on the screen, otherwise nothing is printed.

An if expressions often has one or more accompanying else or else if keywords. These accompanying keywords can be used to further control the flow of a program. Take the following if expression for example:

val a = 4
if (a == 1) {
print("a is equal to one.")
} else if (a == 2) {
print("a is equal to two.")
} else {
print("a is neither one nor two.")
}

The preceding expression first tests whether a is equal to 1. This test evaluates to false so, the following condition has been tested. Surely a is not equal to 2. Hence the second condition evaluates to false. As a result of all previous conditions evaluating to false, the final statement is executed. Hence a is neither one nor two. is printed on the screen.

主站蜘蛛池模板: 宜阳县| 乌海市| 云浮市| 根河市| 张家港市| 宜都市| 梁山县| 梅州市| 铜陵市| 昌图县| 舟曲县| 略阳县| 修武县| 平潭县| 托克逊县| 三台县| 东至县| 页游| 弥渡县| 黎川县| 嫩江县| 赤城县| 文山县| 惠来县| 莱西市| 苏尼特右旗| 高陵县| 临漳县| 宜兴市| 那坡县| 兴仁县| 彰化县| 星子县| 甘德县| 朝阳市| 大洼县| 渑池县| 屯昌县| 岚皋县| 抚顺县| 凤台县|