• No se han encontrado resultados

You use the if…else statement if you want one block of code to execute if the condition is true, and a second, different block of code to execute if the condition is false. This differs from the if statement in that some code in the if…else

statement will execute; the only question is which. By contrast, with the if statement, if the condition is false, no code dependent on the if statement executes.

After the if…else statement completes executing, execution continues with the code following the statement.

The syntax of an if…else statement is shown here:

if (condition) [Code]; else

[Code];

No express condition follows the else statement because the condition is implied as being the negation of the condition following the if statement. In other words, the code following the else statement executes if the condition following the if statement is not true.

Try the following code. It displays in the Output window "You entered a valid test score (0 – 100)" if the input is between 0 and 100, and it displays "You did not enter a valid test score" if the input is less than 0 or greater than 100.

private void btnTest_Click(object sender, EventArgs e) {

string strScore; int intScore;

strScore = txtInput.Text;

intScore = Int32.Parse(strScore); if (intScore >= 0 && intScore <= 100) Debug.WriteLine

("You entered a valid test score (0 - 100)"); else

Debug.WriteLine

("You did not enter a valid test score"); Debug.WriteLine("This line will always print"); }

Although you can have an if without an else, as with the if statement, you cannot have an else without an if. This is logical because else means "none of the

above," and without an if there is no "above."

Common Mistakes

Just as with the if statement, I have noticed while teaching introductory programming classes several common syntax mistakes with the if...else statement.

No Else Without an if Expression

You can have an if expression without an else part. However, you cannot have an else part without an if part. The else must be part of an overall if statement. This requirement is logical. The else part works as "none of the above." Without an if part, there is no "above."

As a consequence, in the following code example, placing a semicolon after the Boolean expression following the if keyword will result in a compiler error.

Because curly braces are not used, the if statement ends after the empty statement created by the incorrectly placed semicolon. The Debug.WriteLine statement "The number is even" is not part of the if statement. Consequently, the else part is not part of an if…else statement and therefore will be regarded as an else part without an if part.

private void btnTest_Click(object sender, EventArgs e) {

int num = Int32.Parse(txtInput.Text);

if ( num % 2 == 0 ); // don't put a semicolon here! Debug.WriteLine("The number is even");

else

Debug.WriteLine("The number is odd"); }

Don't Put a Relational Expression After the Else Keyword!

Another common mistake is to place a relational expression in parentheses after the else keyword:

private void btnTest_Click(object sender, EventArgs e) {

int num = Int32.Parse(txtInput.Text); if ( num % 2 == 0 )

Debug.WriteLine("The number is even"); else ( num % 2 == 1 ) // don't do this! Debug.WriteLine("The number is odd"); }

The program will not compile, and the end of the else expression will be highlighted with an error description such as "; expected."

Actually, the error description is misleading. The problem is not that a semicolon is missing. Instead, no relational expression should follow the else keyword. The reason is that the else acts like "none of the above" in a multiple-choice test. If the if expression is not true, the conditional statements connected to the else part execute.

Don't Put a Semicolon After the Else Expression!

Another common mistake is to place a semicolon after the else expression. This will not cause a compiler or run-time error, but it often will cause an illogical result.

For example, in the following code, the Debug.WriteLine statement "The number is odd" will output even if the number input is even:

private void btnTest_Click(object sender, EventArgs e) {

int num = Int32.Parse(txtInput.Text); if ( num % 2 == 0 )

Debug.WriteLine("The number is even"); else; // don't put a semicolon here! Debug.WriteLine("The number is odd"); }

The Debug.WriteLine statement "The number is odd" will execute whether or not the relational expression is true because that Debug.WriteLine statement no longer is part of the if...else statement. Unless you use curly braces, as explained already in connection with the if statement, only the first statement following the else keyword is conditional. That first, conditional statement is the empty statement by virtue of the semicolon following the if expression.

Therefore, the Debug.Write Line statement "The number is odd" is not part of the if…else statement at all.

Curly Braces Needed for Multiple Conditional Statements

As with the if expression, if you want more than one conditional statement to belong to the else part, you must encase the statements in curly braces.

The ifelse if Statement

code, the maximum possible with an if…else statement.

With an if…else if statement, the first block of code whose condition is true executes, and all following blocks of code are skipped. The first block of code follows the if clause, and each succeeding block of code coupled with a condition is an else if clause. You can have as many else if clauses as you want. Finally, you may optionally have an else clause that, as with an if…else statement, acts as "none of the above." After the if…else if statement finishes executing,

execution continues with any code following the statement. The syntax of an if…else if statement is shown here:

if (condition) [Code]; else if (condition) [Code]; else // optional [Code];

Try the following code. It displays in the Output window "The test score is valid" if the input is between 0 and 100, "Test score cannot be less than zero" if the input is less than 0, or "Test score cannot be greater than 100" if the input is greater than 100.

private void btnTest_Click(object sender, EventArgs e) {

string strScore; int intScore;

strScore = txtInput.Text;

intScore = Int32.Parse(strScore); if (intScore >= 0 && intScore <= 100)

Debug.WriteLine("The test score is valid"); else if (intScore < 0)

Debug.WriteLine

("Test score cannot be less than zero"); else

Debug.WriteLine

("Test score cannot be greater than 100"); Debug.WriteLine("This line will always print"); }

Although you can have as many else if clauses as you want, none can appear after an else clause. The else clause is optional; it serves the function of "none of the above."

Documento similar