## Section 3.5

TheifStatement

THE FIRST OF THE TWO BRANCHING STATEMENTS in Java is the

ifstatement, which you have already seen in Section 1. It takes the formif (boolean-expression)statement-1elsestatement-2As usual, the statements inside an

ifstatements can be blocks. Theifstatement represents a two-way branch. Theelsepart of anifstatement -- consisting of the word "else" and the statement that follows it -- can be omitted.Now, an

ifstatement is, in particular, a statement. This means that eitherstatement-1orstatement-2in the aboveifstatement can itself be anifstatement. A problem arises, however, ifstatement-1is anifstatement that has noelsepart. This special case is effectively forbidden by the syntax of Java. Suppose, for example, that you typeif ( x > 0 ) if (y > 0) System.out.println("First case"); else System.out.println("Second case");Now, remember that the way you've indented this doesn't mean anything at all to the computer. You might think that the

elsepart is the second half of your "if (x > 0)" statement, but the rule that the computer follows attaches theelseto "if (y > 0)", which is closer. That is, the computer reads your statement as if it were formatted:if ( x > 0 ) if (y > 0) System.out.println("First case"); else System.out.println("Second case");You can force the computer to use the other interpretation by enclosing the nested

ifin a block:if ( x > 0 ) { if (y > 0) System.out.println("First case"); } else System.out.println("Second case");These two statements have different meanings: If

x <= 0, the first statement doesn't print anything, but the second statement prints "Second case.".Much more interesting than this technicality is the case where

statement-2, theelsepart of theifstatement, is itself anifstatement. The statement would look like this (perhaps without the final else part):if (boolean-expression-1)statement-1else if (boolean-expression-2)statement-2elsestatement-3However, since the computer doesn't care how a program is laid out on the page, this is almost always written in the format:

if (boolean-expression-1)statement-1else if (boolean-expression-2)statement-2elsestatement-3You should think of this as a single statement representing a three-way branch. When the computer executes this, one and only one of the three statements --

statement-1,statement-2, orstatement-3-- will be executed. The computer starts by evaluatingboolean-expression-1. If it istrue, the computer executesstatement-1and then jumps all the way to the end of the outer if statement, skipping the other twostatements. Ifboolean-expression-1isfalse, the computer skipsstatement-1and executes the second, nested if statement. To do this, it tests the value ofboolean-expression-2and uses it to decide betweenstatement-2andstatement-3.Here is an example that will print out one of three different messages, depending on the value of a variable named

temperature:if (temperature < 50) System.out.println("It's cold."); else if (temperature < 80) System.out.println("It's nice."); else System.out.println("It's hot.");If

temperatureis, say, 42, the first test istrue. The computer prints out the message "It's cold", and skips the rest -- without even evaluating the second condition. For a temperature of 75, the first test isfalse, so the computer goes on to the second test. This test istrue, so the computer prints "It's nice" and skips the rest. If the temperature is 173, both of the tests evaluate tofalse, so the computer says "It's hot" (unless its circuits have been fried by the heat, that is).You can go on stringing together "else-if's" to make multi-way branches with any number of cases:

if (boolean-expression-1)statement-1else if (boolean-expression-2)statement-2else if (boolean-expression-3)statement-3. . // (more cases) . else if (boolean-expression-N)statement-Nelsestatement-(N+1)The computer evaluates boolean expressions one after the other until it comes to one that is

true. It executes the associated statement and skips the rest. If none of the boolean expressions evaluate totrue, then the statement in theelsepart is executed. This statement is called a multi-way branch because only one of the statements will be executed. The finalelsepart can be omitted. In that case, if all the boolean expressions are false, none of the statements is executed. Of course, each of the statements can be a block, consisting of a number of statements enclosed between { and }. (Admittedly, there is lot of syntax here; as you study and practice, you'll become comfortable with it.)

As an example of using

ifstatements, lets suppose thatx,y, andzare variables of typeint, and that each variable has already been assigned a value. Consider the problem of printing out the values of the three variables in increasing order. For examples, if the values are 42, 17, and 20, then the output should be in the order 17, 20, 42.One way to approach this is to ask, where does

xbelong in the list? It comes first if it's less than bothyandz. It comes last if it's greater than bothyandz. Otherwise, it comes in the middle. We can express this with a 3-wayifstatement, but we still have to worry about the order in whichyandzshould be printed. In pseudocode,if (x < y && x < z) { output x, followed by y and z in their correct order } else if (x > y && x > z) { output y and z in their correct order, followed by x } else { output x in between y and z in their correct order }Determining the relative order of

yandzrequires anotherifstatement, so this becomesif (x < y && x < z) { // x comes first if (y < z) System.out.println( x + " " + y + " " + z ); else System.out.println( x + " " + z + " " + y ); } else if (x > y && x > z) { // x comes last if (y < z) System.out.println( y + " " + z + " " + x ); else System.out.println( z + " " + y + " " + x ); } else { // x in the middle if (y < z) System.out.println( y + " " + x + " " + z); else System.out.println( z + " " + x + " " + y); }You might check that this code will work correctly even if some of the values are the same. If the values of two variables are the same, it doesn't matter which order you print them in.

Note, by the way, that even though you can say in English "if x is less than y and z,", you can't say in Java "

if (x < y && z)". The&&operator can only be used between boolean values, so you have to make separate tests,x<yandx<z, and then combine the two tests with&&.There is an alternative approach to this problem that begins by asking, "which order should

xandybe printed in?" Once that's known, you only have to decide where to stick inz. This line of thought leads to different Java code:if ( x < y ) { // x comes before y if ( z < x ) System.out.println( z + " " + x + " " + y); else if ( z > y ) System.out.println( x + " " + y + " " + z); else System.out.println( x + " " + z + " " + y); } else { // y comes before x if ( z < y ) System.out.println( z + " " + y + " " + x); else if ( z > x ) System.out.println( y + " " + x + " " + z); else System.out.println( y + " " + z + " " + x); }Once again, we see how the same problem can be solved in many different ways. The two approaches to this problem have not exhausted all the possibilities. For example, you might start by testing whether

xis greater thany. If so, you could swap their values. Once you've done that, you know thatxshould be printed beforey.

Finally, let's write a complete program that uses an

ifstatement in an interesting way. I want a program that will convert measurements of length from one unit of measurement to another, such as miles to yards or inches to feet. So far, the problem is extremely under-specified. Let's say that the program will only deal with measurements in inches, feet, yards, and miles. It would be easy to extend it later to deal with other units. The user will type in a measurement in one of these units, such as "17 feet" or "2.73 miles". The output will show the length in terms ofeachof the four units of measure. (This is easier than asking the user which units to use in the output.) An outline of the process isRead the user's input measurement and units of measure Express the measurement in inches, feet, yards, and miles Display the four resultsThe program can read both parts of the user's input from the same line by using

TextIO.getDouble()to read the numerical measurement andTextIO.getlnWord()to read the units of measure. The conversion into different units of measure can be simplified by first converting the user's input into inches. From there, it can be converted into feet, yards, and miles. We still have to test the input to determine which unit of measure the user has specified:Let measurement = TextIO.getDouble() Let units = TextIO.getlnWord() if the units are inches Let inches = measurement else if the units are feet Let inches = measurement * 12 // 12 inches per foot else if the units are yards Let inches = measurement * 36 // 36 inches per yard else if the units are miles Let inches = measurement * 12 * 5280 // 5280 feet per mile else The units are illegal! Print an error message and stop processing Let feet = inches / 12.0 Let yards = inches / 36.0 Let miles = inches / (12.0 * 5280.0) Display the resultsSince

unitsis aString, we can useunits.equals("inches")to check whether the specified unit of measure is "inches". However, it would be nice to allow the units to be specified as "inch" or abbreviated to "in". To allow these three possibilities, we can checkif (units.equals("inches") || units.equals("inch") || units.equals("in")). It would also be nice to allow upper case letters, as in "Inches" or "IN". We can do this by convertingunitsto lower case before testing it or by substituting the functionunits.equalsIgnoreCaseforunits.equals.In my final program, I decided to make things more interesting by allowing the user to enter a whole sequence of measurements. The program will end only when the user inputs 0. To do this, I just have to wrap the above algorithm inside a

whileloop, and make sure that the loop ends when the user inputs a 0. Here's the complete program, followed by an applet that simulates it.public class LengthConverter { /* This program will convert measurements expressed in inches, feet, yards, or miles into each of the possible units of measure. The measurement is input by the user, followed by the unit of measure. For example: "17 feet", "1 inch", "2.73 mi". Abbreviations in, ft, yd, and mi are accepted. The program will continue to read and convert measurements until the user enters an input of 0. */ public static void main(String[] args) { double measurement; // Numerical measurement, input by user. String units; // The unit of measure for the input, also // specified by the user. double inches, feet, yards, miles; // Measurement expressed in // each possible unit of // measure. TextIO.putln("Enter measurements in inches, feet, yards, or miles."); TextIO.putln("For example: 1 inch 17 feet 2.73 miles"); TextIO.putln("You can use abbreviations: in ft yd mi"); TextIO.putln("I will convert your input into the other units"); TextIO.putln("of measure."); TextIO.putln(); while (true) { /* Get the user's input, and convert units to lower case. */ TextIO.put("Enter your measurement, or 0 to end: "); measurement = TextIO.getDouble(); if (measurement == 0) break; // terminate the while loop units = TextIO.getlnWord(); units = units.toLowerCase(); /* Convert the input measurement to inches. */ if (units.equals("inch") || units.equals("inches") || units.equals("in")) { inches = measurement; } else if (units.equals("foot") || units.equals("feet") || units.equals("ft")) { inches = measurement * 12; } else if (units.equals("yard") || units.equals("yards") || units.equals("yd")) { inches = measurement * 36; } else if (units.equals("mile") || units.equals("miles") || units.equals("mi")) { inches = measurement * 12 * 5280; } else { TextIO.putln("Sorry, but I don't understand \"" + units + "\"."); continue; // back to start of while loop } /* Convert measurement in inches to feet, yards, and miles. */ feet = inches / 12; yards = inches / 36; miles = inches / (12*5280); /* Output measurement in terms of each unit of measure. */ TextIO.putln(); TextIO.putln("That's equivalent to:"); TextIO.put(inches, 15); TextIO.putln(" inches"); TextIO.put(feet, 15); TextIO.putln(" feet"); TextIO.put(yards, 15); TextIO.putln(" yards"); TextIO.put(miles, 15); TextIO.putln(" miles"); TextIO.putln(); } // end while TextIO.putln(); TextIO.putln("OK! Bye for now."); } // end main() } // end class LengthConverter

[ Next Section | Previous Section | Chapter Index | Main Index ]