Monday, March 14, 2016

Intro To Java: Section 3.2 - Decision Making

In this section we will learn how to use control structures to make decisions in Java.

Watch 3.2 Lecture Video

Equality and Relational Operators

Computers are much more than calculators which take input and return formatted output. They can also make decisions using that data. Java makes it extremely easy to make decisions using if then conditional statements. Essentially they work just as they sound - The JVM will check to see if a certain condition is met, and if it is, it will perform a certain set of actions. The three most basic ways you can compare values using if/else statements are checking if two values are equal to one another or if one value is greater or less than the other value. The operators we use to compare values are known as equality and relational operators.

If then statements follow the syntax shown below:

if(conditions){
     //Code to execute in brackets
}

Equality and Relational Operators

You should memorize all the operators below. They are easy to remember and you will use them often.

NameOperatorDescriptionExample
Equal to == Checks if two values are equal if(x==y){}
Not equal to != Checks if two values are not equal if(x!=y){}
Less than < Checks if the first value is less than the second value if(x<y){}
Greater than > Checks if the first value is greater than the second value if(x>y){}
Less than or equal to <= Checks if the first value is less or equal to than the second value if(x<=y){}
Greater than or equal to >= Checks if the first value is greater than or equal to the second value if(x>=y){}

If-Then Statements With Equality

Equality can be assessed using the equality operator "==". We always use two equal signs to determine if two values are equal instead of one because the one equal sign operator is reserved for assigning values. Additionally, the not equals operator "!=" is used to determine if two values are not equal to each other. The following lines of code check to determine what the value of x is and print out a corresponding message based on what the value of x is.

public class EqualityTest{

     public static void main(String []args){
        int x = 5;
        if(x==5){
            System.out.println("x is equal to 5");
        }
        if(x!=5){
            System.out.println("x is not equal to 5");
        }
     }
}

The output of the program is as follows because x is in fact equal to 5. Note that if you change the value of x the second message will be printed instead of the first one.

x is equal to 5

If-Then Statements With Greater/Less Than

In addition to checking for equality, it is also extremely useful to be able to tell if one value is greater than or less than another value. This can be done using the greater than operator ">" and the less than operator "<". Combinations of these can be made with an equals sign to create the greater than or equal to ">=" operator and the less than or equal to "<=" operator.

The example below checks if one value is greater than another and prints out which value is greater.

public class GreaterLessThan{

     public static void main(String []args){
        //Initialize Variables
        double x = 5.0;
        double y = 10.0;
        //Check Values
        if(x>y){
            System.out.println("x is greater than y");
        }
        if(x<y){
            System.out.println("x is less than y");
        }
        if(x==y)
        {
            System.out.println("x is equal to y");
        }
        
     }
}

In this case the output is as follows, because x is less than y. Note that if you change the values of x and y the output can be different.

x is less than y

If Then Else Statements

In addition to if then statements, you can add an else block to create if then else statements. The "else" part of the statement is executed when the if statement is not executed. In other words, if the first condition is not met, it will execute the "else" statement. This helps shorten your code and allows you to use less if then statements. The example below checks if x is greater than or equal to y, and if not it prints out a message saying that x must be less than y.

public class IfElseExample{

     public static void main(String []args){
        //Initialize Variables
        int x = 10;
        int y = 20;
        
        //If Then Else Statement
        if(x>=y){
            //If x is greater than or equal to y
            System.out.println("x is greater than or equal to y");
        }
        else
        {
            //This code is executed if the first block is not executed, so x must be less than y
            System.out.println("x must be less than y");
        }
        
     }
}

The output is as follows, because x is less than y, and not greater than or equal to y, the else block is executed.

x must be less than y

Else If Statements

In addition to the if then else statements shown above, it is possible to have "else if" statements. They function similarly to else statements, but they also have conditions. So if the first condition is not met, Java will check the second, third, fourth, fifth conditions and so on. The example below quite simply prints out whether the value is equal to one, two, or not one of those two values.

public class ElseIfExample{
 
 public static void main(String[] args) {
  int x = 2;
  if(x==1){
   System.out.println("x is equal to one");
  }
  else if(x==2){
   System.out.println("x is equal to two");
  }
  else
  {
   System.out.println("x is not equal to one or two");
  }
 }

}
x is equal to two

Naturally the output is "x is equal to two" because the second condition is satisfied. Note that it stops once the condition is satisfied - the first block (x==1) is skipped and final else block is not executed.

Nested If Statements

It is possible to add if statements within if statements - this is known as nesting. This allows you to check for multiple things. The example below the age of the user based on if they're at or under the age of 10. It then determines if they are male or female after determining if they are 10 years old or younger with a second if statement within the first.

public class NestedExample{

 public static void main(String[] args) {
  
  //Nested If Statement Example
  int age = 6;
  boolean isMale = true;
  
  //Check to see if user is under the age of 10 and is a male
  if(age<=10){
   if(isMale==true){
    System.out.println("The user is a male under the age of 10");
   }
   else{
    System.out.println("The user is a female under the age of 10");
   }
  }
  else{
   System.out.println("The user is over the age of 10");
  }

 }

}

 

The user is a male under the age of 10

Multiple Conditions With And/Or

It is possible to have multiple conditions in a single if statement. This can be used as an alternative to nested if statements. The example below produces the same types of output as the previous example, but this uses the logical AND operator "&&". This means both conditions must be true for the block to execute. You can add as many additional conditions to the statement as you want.

public class Test {

 public static void main(String[] args) {
  
  //Example Using AND
  int age = 6;
  boolean isMale = false;
  
  //Check if user is under the age of 10 and is a male
  if(age<=10 && isMale==true){
   System.out.println("The user is a male under the age of 10");
  }
  //Check if user is under age of 10 and is female
  else if (age<=10 && isMale==false){
   System.out.println("The user is a female under the age of 10");
  }
  //User is over the age of 10
  else
  {
   System.out.println("The user is over the age of 10");
  }
  
 }
}
The user is a female under the age of 10

The output is "The user is a female under the age of 10" because the first condition is not satisfied (the user is not a male) so it continues on to the second block (the user is a female age 10 or younger).

The logical OR operator is made using two vertical bars "||" (should be located above the enter/return key). When you use OR operators if EITHER of the conditions are true in the if statement, the block will be executed.

public class Test {

 public static void main(String[] args) {
  
  //Example Using OR
  int age = 66;
  boolean isMale = true;
  
  //Check to see if the user is under the age of 10 OR if they are male
  if(age<=10 || isMale==true){
   System.out.println("The user is a male and/or is under the age of ten");
  }
  //If they are not a male OR aged < = 10 they MUST be female AND over the age of 10
  else
  {
   System.out.println("The user must be a female over the age of 10");
  }

 }
}
The user is a male and/or is under the age of ten

The output states that the user is a male and/or is under the age of ten because the user is a male. Even though they are aged 66 the first block is still executed. If this used an AND operator instead of an OR operator like the previous example, the first block would not have been executed. The else block of code will only be executed if the user is over the age of 10 and is a female - because that is the only logical thing that follows if the user is not a male or aged 10 or younger.

Combining/Multiple Operators

In addition to using a single and/or operator, it is possible to use multiple. You can separate each comparison using parenthesis. The example below prints out information based on the user's age, sex, and hair color.

 

The user is a male over age 30 AND/OR they have blond hair

Note what this code is doing. First, it checks if they are a male over the age of thirty, and then it checks if they have blond hair. If either of these conditions are true, the first message is printed. The second condition (haircolor=='R') checks to see if the user's hair color is red - this block will only be executed if the user has red hair and is not a male over age thirty. Try changing the values of the variables to see how it affects the results.

Additionally, notice that you do not have to check if "isMale==true" in the first condition - you can simply type the name of the boolean to check boolean values. If the boolean is true Java will execute the code. In other words, "if(isMale){}" is equivalent to "if(isMale==true){}". It's slightly shorter to type it this way.

public class Test {

 public static void main(String[] args) {
 
  //Example - Combining AND and OR
  
  int age = 43;
  boolean isMale = true;
  char hairColor = 'R'; //Red hair (R), Brown hair (B), or Blond Hair (L) 
  
  //Check to see if they are a male over the age of 30 OR if they have blond hair
  if((isMale && age>=30) || hairColor=='L'){
   System.out.println("The user is a male over age 30 AND/OR they have blond hair");
  }
  else if(hairColor=='R'){
   System.out.println("The user is not a male over age 30 and their hair color is Red.");
  }

 }
}

0 comments:

Post a Comment