Suppose that a program is being written that will display the word version of a two-digit integer between 20 and 59. For example, the integer 32 will be displayed in words as thirty-two. The following code could be used to write the part that will appear before the hyphen (assume that n is an int variable): if(n>=20 && n<30) System.out.println("Twenty"); While this performs the intended task, it is actually quite inefficient. The reason is that the computer will check every condition even though only one of them can be true. For example, suppose that n = 28. The first condition is true, so the computer displays Twenty. Now the computer checks all of the other conditions which are all false (and cannot possibly be true at this point). Checking conditions slows the computer down. While this may not be a big deal in this small situation with only four if statements, imagine large, commercial software in which thousand and millions of decisions are being made. The time checking false conditionals would be excessive. So how can we improve upon the previous code? By combining all of the if statements into one long statement called an if..else..if statement. Here is what it would look like: if(n>=20 && n<30) System.out.println("Twenty") One more thing If the value of n was outside the range of 20-59, nothing will happen. For instance, the value 75 does not make any of the conditions true, so nothing is displayed. If we can be sure that n will not be outside the range 20-59, we could write the code as follows: if(n>=20 && n<30) System.out.println("Twenty") In closing, use an if..else..if only when you are coding 3 or more conditional statements that are all based on the same variable or expression. For example, the following could not be converted to an if..else..if: if(x==1) System.out.println("One"); More than one of these conditions can be true, since they are based on different variables. So an if.else..if would not make sense.
|
|||||||||||
© DanShuster.com