Principle 3.6.1. If Statement.
The if statement has the following syntax:
if (boolean expression)
contained statement;
OneRowNim
class. One problem is that we would describe a One Row Nim game as two players taking turns until there are no more sticks. An object using OneRowNim
would need a way to repeatedly execute a group of statements. One command in Java that controls the repetition of a block of statements is called a while loop. We will consider it later in this section.takeSticks()
:public void takeSticks(int num)
{ nSticks - num;
player = 3 - player;
}
game.takeSticks(5)
will remove 5 sticks even though the rules of One Row Nim say that you must remove 1, 2, or 3. While one might assume that the user interface should prevent the user from breaking this rule, it is a far better design if it was dealt with in OneRowNim
. To do this we need a Java structure that executes different statements depending on whether the parameter is greater than 3, less than 1, or between 1 and 3. The Java if-else statement has this capability. A fuller treatment of control structures appears in Chapter 6, but in this section, we will briefly introduce a couple of simple control structures. This will enable us to write programs that take more interesting actions.if (boolean expression)
contained statement;
boolean expression
is an expression that is either true
or false
. We have seen examples of boolean expressions that involve int
variables, int
values, and the inequality or equality operators. A method call to a method with a boolean
result type is another example of a boolean
expression. Given this description of if statement syntax, the following are examples of valid if statements. For readability, we usually write an if statement with its contained statement indented on the next line:if (true)
System.out.println("Hello");
if (nSticks <= 0)
System.out.println("game is over");
if true // Parentheses are missing
System.out.println("Hello");
if (nSticks <= 0) return // Semicolon missing
if ("true") return; // "true" is not a boolean
if (true) "Hello"; // "Hello" is not a statement
false
and run again. What does it print out? Trace through the code with Show CodeLens.==
(equal), !=
(not equal), <
, >
, <=
, >=
. The double equal sign ==
is used in if statements and other control structures to test a variable’s value. One equal sign (=
) is used to assign a value to a variable like player = 1;
, but two equal signs (==
) are used to test the variable’s value, so that player == 1
will return true
or false
.getPlayerString()
method for the OneRowNim
class.public String getPlayerString()
{
if (player == 1)
return "Player One"; // Exit the method
if (player == 2)
return "Player Two"; // Exit the method
return "Player error"; // Exit the method
}
getPlayerString()
method.player == 1
is true, the string “Player One” is returned to the calling method and the getPlayerString()
method exits at this point. If it is false, then player == 2
should be true (if we have a consistent state) and the string “Player Two” should be returned and the method exited. Thus, if we have a consistent state — that is, if player
has value 1 or 2—then the third return
statement should never be reached.if (player == 1)
{
String s = "Player One";
System.out.print(s);
System.out.println(" plays next");
System.out.println("The game is not over");
}
player == 1
is true, then all four statements in the contained compound statement will be executed. Note here that we are declaring the local variable, s
, in this block. Its scope would extend only to the end of the block. Note also that when we use a compound statement, the compound statement itself is not followed by a semicolon because it is already enclosed in braces.if (condition1)
System.out.println("One");
System.out.println("Two"); //Not part of if statement
println()
is not part of the if statement. To include it in the if statement, you must enclose both println()
statements within braces:if (condition1)
{ System.out.println("One");
System.out.println("Two");
}
if-else
Statement
else
clause into the structure. This allows us to execute either of two separate statements (simple or compound) as the result of one boolean expression. For example, the statementif (player == 1)
System.out.println("Player One");
else
System.out.println("Player Two");
player == 1
is true. Otherwise, it will print “Player Two”.if (boolean expression)
statement1;
else
statement2;
if
is followed by a parenthesized boolean expression, which is followed by statement1, which may be either simple or compound. If statement1 is a simple statement, then it is followed by a semicolon. The else clause follows immediately after statement1. It begins with the keyword else
, which is followed by statement2, which can also be either a simple or compound statement. Note that there is no boolean expression following the else
keyword. In an if-else statement, the boolean expression following the keyword if
goes with both the if and else clauses.int
variable num
that will contain one of the values \(0\text{,}\) \(1\text{,}\) or \(2\) unless there has been an error assigning a value to it. Suppose that we want to write code that will write out the English word for the value in num
. In the example shown in Figure 3.6.8 there are three alternatives plus an error state. Here is the Java code for this example:takeStick()
method to make use of the if-else instead of the somewhat obscure statement :player = 3 - player;
public String takeSticks(int num)
{
nSticks = nSticks - num;
if (player == 1)
player = 2; // From 1 to 2
else
player = 1; // From 2 to 1
}
takeSticks()
involves four lines of code instead of one but is simpler to understand. The if
-statement tests whether the value of player
is \(1\text{.}\) If it is, the value is changed to \(2\text{.}\) If the value of player
is not \(1\text{,}\) then the value must be \(2\) and so the value is changed to \(1\text{.}\) Both versions of the code will give precisely the same result, a programmer could choose to write the code either way.boolean
parameter. public String getStatus(boolean isDone)
{
if (isDone)
return "Done";
else
return "Not Done";
}
getStatus()
method, using the figures in this section as a guide. The if-else structure should be drawn exactly as shown in Figure 3.6.7. It should have a single entry point that leads directly to the top of a diamond-shaped box that contains a boolean condition. There should be two branches coming out of the condition box. The one going to the right is the true case, and the one going to the left is the false case. Each of these branches should contain one rectangular box, which contains the statements that would be executed in that case. The left and right branches should be connected by a circular symbol that is aligned directly under the diamond box whose conditions it connects. There should be a single exit arrow pointing directly down.getPlayerName()
that returns a String
. It should return “Ann”, “Bill”, “Cal”, or “Error” when the value of player
is respectively 1, 2, 3, or any other value.OneRowNim
is such an example.sumSquares(3)
should return the value \(14\) since \(1*1 + 2*2 + 3*3 = 1 + 4 + 9 = 14\text{.}\)
num
gets assigned an initial value of \(1\) before the while
statement. Note also that the boolean
expression num < max
in parentheses after while
states the condition for which we wish to continue summing squares. Finally note that the last statement in the block following the boolean
expression adds \(1\) to num
–that is, this variable is updated at the end of the block.while ( loop entry condition )
{
loop body;
}
while
statement is executed, the loop entry condition is evaluated and if this evaluates to false
, execution continues at the statement immediately after the loop body. If the loop entry condition evaluates to true
, the loop body is executed and then the entry condition is evaluated again. The loop body continues to be executed until the loop entry condition evaluates to false
.while
statement accomplish a task, the variable or variables in the loop entry condition must be initialized correctly before the while
statement and these variables must be correctly updated at the end of the loop body. We can refer to the initializer statement followed by a while
statement as a while structure. We can restate the above guidelines as a design principle:InitializerStatements; // Initializer
while (loop entry condition) { // Bound test
Statements; // Loop body
UpdaterStatements; // Updater
}
sumSquares(-3)
is executed, the loop body will be skipped, because the loop entry condition num
<= max
is false to begin with. No iterations will be performed, and the algorithm will simply return the value \(0\text{.}\)
sumSquares()
method to define a method named sumCubes()
that sums the cubes of integers from a minimum value up to a maximum value and returns that sum. sumCubes()
should have two parameters that will store the minimum and maximum values. Thus the method call sumCubes(2,3)
should return \(35\) since \(2*2*2 + 3*3*3 = 8 + 27 = 35\text{.}\)
sumSquares
method below as a guide, define a method named sumCubes(min, max)
that sums the cubes of integers from a minimum value up to a maximum value and returns that sum.