A Decision Structure requires a Boolean expression, which is a statement that will provide you with a true or a false value for a given relation. Performing a boolean expression requires the use of relational operators. In this chapter, we will discuss statements such as the if-statement that require to have a boolean expression to perform an action.
The if statement looks as follows:
if(<boolean expression>)
{
// statements
}
Example: Suppose that we are writing a program that decides what clothes you should wear today based on the current temperature. The program shall ask the user to enter the temperature
The basic skeleton of the code starts as follows:
import java.util.Scanner;
public class DecisionExample01{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.println("What is the current temperature?");
int temp = input.nextInt();
}
}
Suppose that we are in El Paso, TX, and we don't know what cold is… But we still want to decide what to wear. In case the temperature is greater than or equal to 65 you can wear shorts and a t-shirt. Otherwise, you can wear pants and jacket.
if( temp >= 65 )
{
System.out.println("wear t-shirt and shorts");
}
else
{
System.out.println("wear pants and jacket");
}
There are situations (especially when you start coding or gaining practice coding your if-statements) where you will find an error such as "else without if." One of the most common reasons is:
· You have a semicolon on the if statement
1. if( temp >= 65 );
2. {
3. System.out.println("wear t-shirt and shorts");
4. }
5. else
6. {
7. System.out.println("wear pants and jacket");
8. }
Java supports Logical Operators. These operators can be demonstrated by using Boolean statements generated by using the truth tables.
The purpose is to “conjunct” two Boolean statements. Using logical AND will require that two statements have to be true to generate a true statement. If one of the statements is false, the resulting statement will be false.
// image
The purpose is to “disjunction” two Boolean statements. Using logical OR will require that at least one statement be true to generate a true statement. If both statements are false, the resulting statement will be false.
// image
The purpose of this statement is to flip the value of the Boolean statement to its opposite value. For example, if the statement is true, “not” true results in false, and “not” false results in true.
The switch case allows us to perform decisions based on the current "state" of a variable. These variables can have the form of int, char, byte, and String.
Example
Re-do problem DecisionExample06.java requesting the user to enter [D], [R], or [I]. Ensure the program uses the switch only with the allowed data types mentioned in class (i.e., int, char, and byte).
Let us first request information from the user. Notice that the variable option will contain the user’s input.
System.out.println("Please enter party [D], [R], [I]");
char option = input.nextLine().charAt(0);
switch( option )
{
case 'D':
System.out.println("you vote Democrat");
case 'R':
System.out.println("you vote Republican");
case 'I':
System.out.println("you vote Independent");
}
}
The switch will hold the variable option that will control the flow of the decision-making. Notice that there are three possible cases: 'D’, ‘R’, or ‘I’. If we test this program as follows:
Please enter party [D], [R], [I]
[I]
You vote Independent
However, if we enter:
Please enter party [D], [R], [I]
[D]
you vote Democrat
you vote Republican
you vote Independent
The switch case allows to determine when a case is satisfied, then executes the case’s scope. However, once the case is satisfied, the program must leave the case immediately, or it will go through all the other cases. Therefore, we need to “break" the flow of decisions. We use the break keyword for this. The new code looks as follows:
case 'D':
System.out.println("you vote Democrat");
break;
case 'R':
System.out.println("you vote Republican");
break;
case 'I':
System.out.println("you vote Independent");
break;
What would happen if the user enters an input that does not belong to D, R, or I? We must address this situation the same way we did with the if-else statement. In the switch case context, an else is called the default. The default keyword permits addressing the remaining cases that are not listed. Typically, it is used to address error messages or feedback to the computer user.
Another situation that we need to address is in case the user provides you with upper and lower case input. In the switch-case, we can list similar cases together by stacking them together. Here is the solution of incorporating the default and the multiple cases
switch( option )
{
case 'D':
case 'd':
System.out.println("you vote Democrat");
break;
case 'R':
case 'r':
System.out.println("you vote Republican");
break;
case 'I':
case 'i':
System.out.println("you vote Independent");
break;
default:
System.out.println("Incorrect Input");
}
What is wrong with this statement?
char option = input.toUpperCase().charAt(0);
Example
Problem 13:
Scanner input = new Scanner(System.in);
System.out.println("Please enter selection [A], [B], [C]");
char packageOption = input.nextLine().charAt(0);
System.out.println("Please enter total of minutes");
int minutes = input.nextInt();
switch( packageOption )
{
case: 'A':
case: 'a':
{
}
case: 'B':
case: 'b':
{
}
case: 'C':
case: 'c':
{
}
default:
System.out.println("Invalid Package Input");
}
if(minutes <= 450)
{
System.out.println("Total bill amount is: $39.99");
}
else
{
int additional = minutes - 450;
double total = (additional * 0.45)+ 39.99;
//double subtotal = additional * 0.45;
//subtotal += 39.99; // same as: subtotal = subtotal + 39.99;
System.out.println("Total bill amount is: $"+total);
}
To compare two values of the Eight Primitive types, we can use the so-called relational operators.
> (greater)
< (less)
>= (greater equal to)
<= (less than or equal to)
== (equal)
!= (not equal)
These operators are called relational operators because they compare two values (one on the left side and another to the right side) to generate a boolean value. For example, let us interact with Java to test the relational operators with numeric values:
--> 10 > 5
true
--> 10 >= 5
true
--> 10 < 5
false
--> 10 <= 5
false
--> 10 == 5
false
--> 10 != 5
true
Let us now developed a code named RelationalOperators that shows whether the operations we are evaluating is true or false by declaring some variables x and y (lines 3 and 4):
1 public class RelationalOperators{
2 public static void main(String[] args) {
3 int x = 4;
4 int y = 5;
5 System.out.print("Is 4 < 5? ");
6 System.out.println(x < y);
7 System.out.print("Is 4 == 5? ");
8 System.out.println(x == y);
9 }
10 }
Computer Terminal:
Is 4 < 5: true
Is 4 == 5: false
Computer Terminal and the following lines from the example above are the output that our code produces once we have saved it, compiled it, and run it. For further practice, you can take the next cases and check their outputs.
> int x = 10
> int y = 10
> x > y
false
> x >= y
true
> x <= y
true
> x != y
false
> x == y
true
To compare Strings we will need to use the functionality of .equals() or .compareTo().
Let us interact with Java to demonstrate the .equals() and the .compareTo() methods.
Let us first declare three Strings
> String s1 = "hello"
> String s2 = "hi"
> String s3 = "hello"
When the == relational operator is used with s1 and s2, you obtain what you expect
> s1 == s2
false
However, when the operator is used with s1 and s3, a surprise appears when the following statement is executed:
> s1 == s3
False
The reason is that the == is useful only for the eight primitive types because Java also uses the == to check "location" where the String is stored in memory (but we will talk about this later on). If we are interested in comparing the content of the strings, we need to use the .equals() method as follows:
> s1.equals(s3)
true
> s1.equals(s2)
False
For equality, you can use the .equals().
> s1 > s2
Static Error: Illegal comparison: cannot compare a String to a String
Remember that the relational operators can only be applied to the eight primitive types, so here the >, <, >=, <= operators cannot be used. Instead, if you would like to check the order of the strings, we use the .compareTo() method
> s1.compareTo(s2)
-1
The .compareTo() will return a number and a sign (i.e., positive, or negative).
If the value is negative, that means that the String to the left (i.e., s1) is "smaller" than the String to the right (i.e., s2) lexicographically speaking.
If the value is positive, that means that the string to the left (i.e., s2) is “larger” than the string to the right (i.e., s1) lexicographically speaking.
For example, let us make a couple of comparisons and evaluations:
> s2.compareTo(s1)
1
> s1.compareTo(s2)
-4
> s2.compareTo(s1)
4
> String s3 = "he"
> s1.compareTo(s3)
3
> s3.compareTo(s1)
-3
> String s4 = "Hello"
> s1
"hello"
> s4
"Hello"
> s1.compareTo(s4)
32
> String s5 = "hello"
> s1
"hello"
> s5
"hello"
> s1.compareTo(s5)
0
> s1.compareTo(s2) > 0
false
>