else if

What if you have more than two possibilities? You can test for them one-by-one using else if. For example, imagine that a truck belongs to one of three weight categories: floating, light, and heavy.

i​f​ ​(​t​r​u​c​k​W​e​i​g​h​t​ ​<​=​ ​0​)​ ​{​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​ ​f​l​o​a​t​i​n​g​ ​t​r​u​c​k​​n​"​)​;​
}​ ​e​l​s​e​ ​i​f​ ​(​t​r​u​c​k​W​e​i​g​h​t​ ​<​ ​4​0​0​0​0​.​0​)​ ​{​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​ ​l​i​g​h​t​ ​t​r​u​c​k​​n​"​)​;​
}​ ​e​l​s​e​ ​{​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​ ​h​e​a​v​y​ ​t​r​u​c​k​​n​"​)​;​
}​

You can have as many else if clauses as you wish. They will each be tested in the order in which they appear until one evaluates as true. The in the order in which they appear part is important. Be sure to order your conditions so that you don’t get a false positive. For instance, if you swapped the first two tests in the above example, you would never find a floating truck because floating trucks are also light trucks. The final else clause is optional, but it’s useful when you want to catch everything that did not meet the earlier conditions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset