Навигация
 
  •  Главная
•  Программирование
•  Веб-программирование
•  Заработок в сети
•  Продвижение сайта
•  Дизайн
 
 
 
 
 
 
 
 
 
 
 
   
 
 
 
 
 
 
Навигация
 
  •  Главная
•  Форум
•  Доска объявлений
•  Биржа труда
•  О нас
 
 
 
     
  •   Программисты.kz » Программирование » Java » Уроки Java » If Statements  

      Реклама на сайте:
Голосуй за Programmers.kz

  If Statements  
    |   18-12-2009, 19:40   |   Опубликовал: КазКиберГетик  : 171  
 

Java Unit 6

If Statements

6.1  The Syntax of if Statements and Arithmetic Conditions

6.2  Multiple Alternatives and Nested ifs

6.3  Logical Operators, Compound Expressions, and Boolean Variables

6.4  Comparing Objects

6.5  A Final Example, the Character Type, and Some Common Errors

6.1   The Syntax of if Statements and Arithmetic Conditions

This section gives several examples of if statements.  In this first example, if a certain condition holds true, the single line of code immediately following it is executed.  If the condition does not hold true, then that line of code is not executed.  In either case, any lines of code in the program following that line of code are executed.

if(condition)

  statement;

Notice that the keyword if and the set of parentheses containing the condition do not form an independent line of code.  They should not be followed by a semicolon.  If the condition is followed immediately by a semicolon, this causes a logic error which is hard to see.  The system tests the truth of the condition.  It doesn’t matter whether the result is true or false.  The semicolon signals the end of the if.  The following line of code would not depend on it and it would simply be executed.

The second example shows an if statement with 2 mutually exclusive alternatives.  In the course of execution, one or the other of the two statements has to be executed, but not both.  Like the line of code containing the if, the else does not form an independent line of code, and should not be followed by a semicolon.  If it is followed by a semicolon then any line of code following it would be executed unconditionally.

if(condition)

  statement1;

else

  statement2;

In both of the examples above, the single statements can be replaced by a block of code enclosed in braces.

if(condition)

{

  statement1;

  statement2;

  …

}

else

{

}

The conditions inside if statements are frequently comparisons between numeric values.  The comparison operators in Java are as follows:

<               less than

<=                        less than or equal to

>               greater than

>=                        greater than or equal to

!=                        not equal to

==                        equal to.  Notice the difference between this and assignment.

In a previous unit the point was made that Java is particular in the way it handles floating point values.  It is important to keep this in mind when doing numeric comparisons, especially when mixing integer and floating point type variables.  If a variable contains an inexact binary representation of a decimal value, the result of the comparison may not be what you have in mind.

It would be possible to write any number of fragments of code illustrating the models shown above.  It may be useful to show the use of the if statement in some class code.  Here is the code for the Cup3 class.  It contains the method to increase the number of seeds in a cup.

public class Cup3

{

  private int seedCount;

  public Cup3()

  {

       seedCount = 0;

  }

  public Cup3(int initialCount)

  {

       seedCount = initialCount;

  }

  public int getSeedCount()

  {

       return seedCount;

  }

  public void setSeedCount(int newCount)

  {

       seedCount = newCount;

  }

  public void increaseSeedCount(int addedNumber)

  {

       seedCount = seedCount + addedNumber;

  }

}

Observe that in spite of the way things are named using words like increase and added, it would be possible to send a negative parameter to the increaseSeedCount() method.  It is possible to use an if statement in the method code to prevent a negative value from being acted on.  A simple attempt to handle this might look like the following:

  public void increaseSeedCount(int addedNumber)

  {

       if(addedNumber > 0)

       {

            seedCount = seedCount + addedNumber;

       }

  }

This is not a complete solution.  It is convenient that the if statement prevents an undesired outcome.  It is not convenient that a programmer could call the method and not be warned that the code to increment was not executed.  Ways of addressing this problem will be taken up later.

6.2   Multiple Alternatives and Nested ifs

Here is a model for an if statement with multiple mutually exclusive alternatives:

if(condition1)

{

  …

}

else if(condition2)

{

  …

}

else

{

}

Any number of else ifs can be used, but this structure has to end with an else.  This final else is the default case if none of the ifs and else ifs hold true.  It is syntactically incorrect to end the structure with an else if.  Sometimes there is no separate statement or block of statements that needs to be executed in the default case.  If so, then the else can be followed immediately by a semicolon or by a pair of braces containing nothing, but the else itself can’t be eliminated.

This structure can be used for a mutually exclusive set of discrete cases as illustrated by the following:

if(x == 1)

{

  //  do something

}

else if(x == 2)

{

  //  do something else

}

else

{

  //  do yet something else

}

Notice that it is also useful for handling sequences of numerical values, either ascending or descending:

if(x <= 1.0)

{

  //  do something

}

else if(x <= 2.0)

{

  //  executed for values > 1.0 and <= to 2.0

}

else if(x <= 3.0)

{

  //  executed for values > 2.0 and <= to 3.0

}

else

{

  //  executed for all values > 3.0

}

In general there are no restrictions on where if statements can appear in program code.  They can occur within the pair of braces delimiting any valid block.  In particular, an if statement and its else or else if statements can appear within a block of code that belongs to another if, else, or else if statement.  When this occurs it is known as a nested if.  The nesting refers to the pattern of pairs of matched braces occurring within other pairs of matched braces.  For ease of reading, it is recommended that each pair be indented one tab from the pair that contains it.  The model when nested only one level deep would look like this:

if(condition1)

{

  if(condition2)

  {

       statement1;

  }

  else

  {

       statement2;

  }

}

else

{

  if(condition3)

  {

       statement3;

  }

  else

  {

       statement4;

  }

}

statement1 is executed if condition1 is true and condition2 is true.

statement2 is executed if condition1 is true and condition2 is not true.

statement3 is executed if condition1 is not true and condition3 is true.

statement4 is executed if condition1 is not true and condition3 is not true.

6.3  Logical Operators, Compound Expressions, and Boolean Variables

Java has the logical operators and, or, and not, symbolized by &&, ||, and !, respectively.  Logical or means one or the other or both conditions hold true.  It is also possible to devise logical expressions which have the meaning of exclusive or, which means one or the other, but not both hold true.  Parentheses can be used in logical expressions to clarify the grouping of different conditions.  Once the logical operators are available it becomes possible to construct complex conditions.

The combination of conditions for the previous example is repeated here:

statement1 is executed if condition1 is true and condition2 is true.

statement2 is executed if condition1 is true and condition2 is not true.

statement3 is executed if condition1 is not true and condition3 is true.

statement4 is executed if condition1 is not true and condition3 is not true.

This code, using the logical operators, is equivalent to the code using nested ifs:

if(condition1 && condition2)

{

  statement1;

}

else if(condition1 && !condition2)

{

  statement2;

}

else if(!condition1 && condition3)

{

  statement3;

}

else if(!condition1 && !condition3)

{

  statement4;

}

else

{

}

It is the programmer’s choice whether to use nested ifs or logical operators.  It is possible to construct arbitrarily complex logical expressions.  Depending on the variables at hand and their meanings, you may have statements involving more than one numerical variable of the following form:

if(x < 5 && y > 12)…

if(x < 5 || y > 12)…

You may also have comparisons involving a single numerical variable that bring up properties of number lines from algebra.  Here are four such examples:

if(x < 5 && x > 12)      Never true:

if(x < 5 || x > 12)      True for values outside of the range from 5 to 12:

if(x > 5 && x < 12)      True for values inside the range from 5 to 12:

if(x > 5 || x < 12)      Always true:

When using if statements, execution of certain blocks of code depends on the truth value of conditions such as numeric comparisons of equality and inequality.  Depending on the values of variables each condition has a value of true or false.  Not only does the system evaluate conditions to arrive at truth values.  Java also has a simple type called boolean that can contain truth values.  true and false are keywords designating the two values a boolean variable can contain.  Here is an example of declaration and assignment:

boolean someResult;

someResult = true;

someResult = false;

The next question to consider is that of notifying the user when one of several possible actions is taken by a method.  The way to do this is by giving the method a type and a return value that signifies which action was taken.  For a method where there are essentially two alternatives, either some action or no action, a boolean return value is a reasonable choice.  The example method is rewritten below to return a value indicating whether the seedCount was increased or not.  This change is significant enough that the cup class containing it is renamed Cup4.

  public boolean increaseSeedCount(int addedNumber)

  {

       if(addedNumber > 0)

       {

            seedCount = seedCount + addedNumber;

            return true;

       }

       else

            return false;

  }

The method is now typed boolean and one of the two boolean values is returned at the end of the two different execution paths through the method.

In code that makes use of the method, a call would take the form illustrated in the following fragment:

boolean callresult;

int moreSeeds = 7;

Cup4 mycup = new Cup4(5);

callresult = mycup.increaseSeedCount(moreSeeds);

After the call it would be possible to take certain actions in the program depending on whether the return value was true or false.  The structure of such actions might be further if statements.  Note that when using boolean values in if conditions, it is not necessary to use a symbol to test equality.  It is sufficient to use a variable containing the truth value by itself.  For example in the method call above, this would be a valid condition:

if(callresult)

  …

It is not recommended because it is difficult to read, but it is also possible to write code in the following form.  The call is embedded in the parentheses.  When the call is made, a truth value is returned.  The action of the if statement depends on this return value.

if(mycup.increaseSeedCount(moreSeeds))

  …

}

            It is also true that in calling code it is not necessary to capture the return value.  It can be ignored and this is not a syntactical error.  For example, this is a valid line of code:

            mycup.increaseSeedCount(moreSeeds);

            Notice that in the method code there were two return statements.  They were in the two mutually exclusive alternatives of an if statement.  Whenever a return statement is encountered this ends the execution of the method.  It is possible to consolidate such a situation by assigning a return value to a variable and returning the variable at the bottom of the method.  Here is the method modified in that way:

  public boolean increaseSeedCount(int addedNumber)

  {

       boolean returnvalue;

       if(addedNumber > 0)

       {

            seedCount = seedCount + addedNumber;

            returnvalue = true;

       }

       else

            returnvalue = false;

       return returnvalue;

  }

6.4  Comparing objects

The general subject of comparing objects, or object references, can be introduced concretely with strings.  Recall that String is a class, and so strings themselves are instances of this class.  The String class implements a method called equals().  This is the method that checks to see whether the contents of two different string objects are the same.  Let two strings be declared and initialized as follows:

String mystring = “Hello World”;

String yourstring = “Hello World”;

The situation can be diagrammed in this way:

Two separate objects exist, containing the same sequence of characters.  Here is an if statement containing a call to the equals() method.  In this situation the condition evaluates to true.

if(mystring.equals(yourstring))

If these string values were assigned to the two references, however, the equals() method would return false:

mystring = “Tra-la-la”;

yourstring = “La-de-dah”;

This is straightforward.  The complication comes when you consider the use of the operator ==.  This tests for equality of reference, not equality of contents.  In other words, it tests to see whether the objects themselves are the same, not whether their contents are the same.  Let the two strings now be declared and initialized as follows:

String mystring = “Hello World”;

String yourstring = mystring;

if(mystring == yourstring)

The situation can be diagrammed in this way:

Only one object exists, with two references to it.  Here is an if statement containing a test of equality of reference.  In this situation the return value would be true.

if(mystring == yourstring)

There are other methods in the String class that support various kinds of comparisons.  Among them are compareTo() and equalsIgnoreCase().  The first of these allows you to compare the contents of strings to see which might come first alphabetically.  The second method allows you to check for equality of contents of strings where small and capital letters don’t make a difference.  This can be useful when taking in input from users.  Complete information on each of these methods can be found in the Java API documentation.

 The same observations that were made for comparing equality of strings can be made for comparing equality of objects in general.  Suppose you have the following two declarations and initializations:

Point2D.Double mypoint = new Point2D.Double(10, 20);

Point2D.Double yourpoint = new Point2D.Double(30, 40);

The contents are different and the objects are different.  Both the equals() method and the == would return false.  Suppose instead that the initializations were as follows:

Point2D.Double mypoint = new Point2D.Double(10, 20);

Point2D.Double yourpoint = new Point2D.Double(10, 20);

Now the equals() method would return true while the == would return false.  Finally consider this case:

Point2D.Double mypoint = new Point2D.Double(10, 20);

Point2D.Double yourpoint = mypoint;

Now both equals() and == would return true.

This description of equals() and == applies to system supplied classes.  However, beware:  equals() will not work this way with classes you have written.  For example, suppose I have the following objects, created using my own class:

Shampoo myshampoo = new Shampoo();

Shampoo yourshampoo = new Shampoo();

No matter what the contents of these objects might be, the equals() method will work exactly like the ==.  In other words, for your classes it is possible to call the equals() method, but it only tests for equality of reference, not equality of contents.  Your class inherits the method equals() from a class above it in the hierarchy.  However, the inherited implementation does not work in the desired way.  How to write an equals() method will be covered in a future unit.

6.5  A Final Example, the Character Type, and Some Common Errors

Some airlines have frequent flyer plans where a customer can get a free ticket to some destination after having traveled a sufficient number of miles using paid tickets.  Typically, different numbers of miles are needed for different destinations, and other conditions also apply.  An outline of such a plan follows.

1.      A customer flying from the U.S. can choose between several different categories of destinations, including:  The U.S.; Elsewhere in North America; Europe; India, Africa, and the Middle East; Asia and the Pacific.  In the discussion that follows the word “destination” will be used to refer to this.

2.      A traveler has to use a different number of miles depending on whether or not the dates of the trip fall during the peak travel season for the destination.  In the discussion that follows the word “peak” will be used to refer to this.

3.      Finally, regardless of season, there are certain holidays when it is not possible to fly on a free ticket unless an additional number of miles is used.  In the discussion that follows the word “holiday” will be used to refer to this.

The information on such a plan can be presented in a table.  Let the numbers in the table be the number of miles that need to be accumulated in order to get a frequent flyer ticket to that destination under those conditions.

Destination:  U.S.

Off peak

Non-holiday

20,000

   

Holiday

40,000

 

Peak

Non-holiday

25,000

   

Holiday

50,000

Destination:  North

Off peak

Non-holiday

35,000

America

 

Holiday

70,000

 

Peak

Non-holiday

35,000

   

Holiday

70,000

Destination:  Europe

Off peak

Non-holiday

40,000

   

Holiday

100,000

 

Peak

Non-holiday

50,000

   

Holiday

100,000

Destination:  India,

Off peak

Non-holiday

80,000

Africa, Middle East

 

Holiday

140,000

 

Peak

Non-holiday

90,000

   

Holiday

140,000

Destination:  Asia,

Off peak

Non-holiday

50,000

Pacific

 

Holiday

120,000

 

Peak

Non-holiday

60,000

   

holiday

120,000

Given this information it would be possible to write an application that did table look up, answering this question:  For some destination and travel dates, what number of accumulated miles is required to get a free ticket?

Suppose the following abbreviations are used:  U, N, E, I, A for the United States, North America, Europe, India, and Asia, respectively; P and O for peak and off-peak, respectively; and H and N for holiday and non-holiday, respectively. You might then have statements like these in the program:

String destination, peakornot, holidayornot;

destination = myterminal.getString(“Enter U, N, E, I, or A for your destination.”);

peakornot = myterminal.getString(“Enter P or O for peak or off-peak.”);

holidayornot = myterminal.getString(“Enter H or N for holiday or non-holiday.”);

if(destination.equalsIgnoreCase(“U”)

{

       if(peakornot.equalsIgnoreCase(“P”))

       {

            if(holidayornot.equalsIgnoreCase(“H”))

            {

                myterminal.println(“50,000 miles.”);

            }

            else

            {

                myterminal.println(“25,000 miles.”);

            }

       }

       else

       {

            …

       }

  …

Notice that you have strings where you expect the user input to be a single character, and you compare the contents of these strings with string constants that contain a single character.  There is nothing wrong with this.  As a matter of fact, it is quite desirable since you are familiar with various useful methods in the String class that allow you to do comparisons.

There is also a simple type char in Java.  We can’t make much use of it yet because the MyTerminalIO class doesn’t have methods that handle it.  It is mentioned here by way of introduction and because it is a possible source of mistakes.  A character constant is set off by single quotes, not double quotes, and the string methods do not apply to it.  Handling characters will be dealt with in more detail later.  In the meantime, the syntax for their declaration and assignment is shown here to distinguish them clearly from strings:

char mychar;

mychar = ‘K’;

Other than the possibility of confusing strings and characters, here is a brief list of some of the common mistakes made when using if statements and testing conditions:

A.    You use “=” rather than “==” when testing equality.

B.     You mistakenly put a “;” at the end of the if, else if, or else.

C.     When using else if, you forget to end the sequence with a simple else.

D.    You forget to use braces to set of blocks of code that belong to conditions.

E.     You mismatch braces when setting off blocks of code.  It is helpful to indent blocks consistently in order to be able to see where one starts and another ends.

F.      When comparing object references you confuse the test for equality of reference, ==, with the test for equality of contents, equals().

G.    You forget that the equals() method does not test for equality of contents on objects of your own classes.


Download MyTerminalIO class

Author: Kirk Scott

Look official permission!


Ключевые теги: Statements, Уроки Java
 
 
 
Уважаемый посетитель, Вы зашли на сайт как незарегистрированный пользователь. Мы рекомендуем Вам зарегистрироваться либо войти на сайт под своим именем.

Обсудить на форуме


Другие статьи по теме:


 
 
 (голосов: 0)
 

  Информация  
     
  Посетители, находящиеся в группе Гости, не могут оставлять комментарии в данной новости.  


 
 
Вход на сайт
 
логин :
пароль :
Напомнить пароль?
Вы не зарегистрированы? Регистрация здесь
 


Наш опрос
   


Статистика
  Всего на сайте: 18
Гостей: 12
Пользователи: - отсутствуют
Роботы: crawl Bot, Google Bot, Yandex Bot, Yahoo Bot, Google AdSense

 


Олимпиады
  2010/09/09 - 17:00, Чт SRM 481
Начало: 2010/09/09 - 17:00, Чт Длительность: 1 ч 35 м

2010/09/15 - 21:00, Ср Member SRM 482
Начало: 2010/09/15 - 21:00, Ср Длительность: 1 ч 35 м

2010/09/25 - 22:00, Сб SRM 483
Начало: 2010/09/25 - 22:00, Сб Длительность: 1 ч 35 м

2010/10/06 - 07:00, Ср SRM 484
Начало: 2010/10/06 - 07:00, Ср Длительность: 1 ч 35 м

2010/10/21 - 17:00, Чт Member SRM 485
Начало: 2010/10/21 - 17:00, Чт Длительность: 1 ч 35 м

 


Партнёры
 
Freeway.kz
Образование в Казахстане и за рубежом: Uchi.kz
Benchmark.kz - компьютерный портал
wWw.informatik.kz
Информационный портал Hi-Tech
 


Реклама
 
 


 
 
 
 
Главная страница   |   Регистрация   |   Добавить новость   |   Правила сайта   |   Статистика   |   Обратная связь
Copyright © 2009 КазКиберГетик & AlexanderMS . Все права защищены...
Made in DLETemplates.Com and by КазКиберГетик © 2009 for programmers.kz. Modifications by КазКиберГетик
  Rambler's Top100