0% found this document useful (0 votes)
12 views12 pages

Java Decision-Making Structures Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views12 pages

Java Decision-Making Structures Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA FUNDAMENTALS

Image taken from [Link]

LESSON 3:
MAKING DECISIONS

✓ If Statement
✓ Relational and Logical
Operators
Prepared by: ✓ If-else and If-else if
Statements
Genalyn D. Villafuerte ✓ Switch Statement
✓ Ternary Operator

COMPUTER PROGRAMMING 2 1
LESSON 3: MAKING DECISIONS

Desired Learning Outcomes


At the end of this lesson, you must be able to:
1. Use Scanner for user input during program execution
2. Use if logic structure as one-way decision
3. Use if-else logic structure and ternary operator as two-way
decision
4. Use nested if, if-else if, and switch logic structures as multi-way
decision
5. Use break and default effectively in a switch statement
6. Compile an application
7. Test to ensure application is complete
8. Run the Java program
Let’s get started!

K-W-L Chart 3
Directions: Fill out the K and W columns in this KWL Chart. Write as
many ideas as you want.
K – What I already W – What I WANT L – What I LEARNED
KNOW about this to know about this about this topic
topic topic

Note: This column is to


be filled out at the end
of the lesson.

COMPUTER PROGRAMMING 2 2
This module gives a complete understanding of Java. This reference will
take you through simple and practical approaches while learning Java
Programming language.

If Statement

An if statement is sometimes called a one-way decision or a single-


alternative selection because there is only one alternative—the true
alternative in a decision. Use the if statement to specify a block of
Java code to be executed if a condition is true.
You could type the entire if statement on one line and it would execute
correctly:
if(score==10) [Link]("The score is perfect");

However, the two-line format for the if statement is more conventional


and easier to read, so you usually type if and the Boolean expression on
one line, press the Enter key, and then indent a few spaces before
coding the next action:
if(score==10)
[Link]("The score is perfect");

The above example makes the decision whether to produce output. It


displays a message when the value of score is 10. Note that the double
equal sign (==) is used to determine equality; it is Java’s equivalency
operator.

Misplacing a Semicolon in an if Statement


There is no semicolon at the end of the first line of the if statement
following the parentheses because the statement does not end there. In
this case, because of the incorrect semicolon, the if statement
accomplishes nothing.

COMPUTER PROGRAMMING 2 3
Relational and Logical Operators

Java has six relational operators used to test primitive or literal


numerical values. These are also used to evaluate if-else and loop
conditions.

Relational Operators Examples


The expression grade>=88 evaluates as true or false depending on the
value assigned to grade.
int grade=99;
if(grade>=88)
[Link]("You’ve got an Honor.");

To evaluate the condition: if(grade >= 88)


if(99 >= 88)
if(true)

Using the Assignment Operator


In this example, the variable honor is assigned a true value when the
expression grade>=88 evaluates as true.
int grade=99;
boolean honor = grade>=88;
if(honor)
[Link]("You’ve got an Honor.");

Java has three logical operators used to combine boolean


expressions into complex tests.

COMPUTER PROGRAMMING 2 4
Logical Operators Examples
In this example, the phrase "You qualify for the scholarship" will print if
both conditions are true. For the message to print, honor must be true
and the absent must be equal to zero.
int absent=0;
int grade=99;
boolean honor = grade>=88;
if(honor && absent == 0)
[Link]("You qualify for the scholarship.");

To evaluate the condition: if(honor && absent == 0)


if(grade >= 88 && absent == 0)
if(99 >= 88 && 0 == 0)
if(True && True)
if(True)

In this example, the phrase "You need tutoring help." prints to the screen
double grade=65;
int absent=2;
boolean honor = grade>=88;
if(!honor && absent<3)
[Link]("You need tutoring help.");

To evaluate the condition: if(!honor && absent < 3)


if(!(grade >= 88) && absent < 3)
if(!(65 >= 88) && 2 < 3)
if(!False && True)
if(True && True)
True

However, in this example, the phrase "You may try out for varsity." does
not print as the student's grade is not above 70 and the absence is not
above 2.
if(grade>70 || absent>2)
[Link]("You may try out for varsity.");

To evaluate the condition: if(grade > 70 || absent > 2)


if(grade > 70 || absent > 2)
if(65 > 70 || 2 > 2)
if(False || False)
if(False)

COMPUTER PROGRAMMING 2 5
If-else and If-else if Statements

The if-else statement provides the mechanism to perform one


action when a Boolean expression evaluates as true and a different
action when a Boolean expression evaluates as false. It is also called
two-way decision or a dual-alternative selection.
The if-else if statement is also called multi-way decision or
multiple-alternative selection.
To build an if-else and if-else if statement, remember the following rules:
• An if-else statement needs a condition or method that is tested
for true/false.
• An optional else or else if statement/s will take care of the
other possibility/ies.
• When you execute an if-else or if-else if statement/s, only
one of the resulting actions takes place depending on the
evaluation of the Boolean expression.
if(score==10)
[Link]("The score is perfect");
else
[Link]("It's not perfect!");

• When you place a block within an if statement, it is crucial to


place the curly braces correctly.
if(hrsWorked > 40){
regPay = 40 * rate;
otPay = (hrsWorked - 40) * 1.5 * rate;
}
else {
regPay = hrsWorked * rate;
otPay = 0.0;
}

COMPUTER PROGRAMMING 2 6
If-else if Statements with the int Data Type
import [Link];

public class NumberChecker {


public static void main(String[] args){
Scanner scan = new Scanner([Link]);
int value = 0;
[Link]("Enter a number:");
value = [Link]();
if(value == 7)
[Link]("That's lucky!");
else if(value == 13)
[Link]("That's unlucky!");
else
[Link]("That is neither lucky nor unlucky!");
}
}

Sample Output:

If-else if Statements with the char Data Type


import [Link];

public class Calculator {


public static void main(String[] args) {
Scanner scan = new Scanner([Link]);
double answer = 0;
char op;
[Link]("Enter a number:");
double num1 = [Link]();
[Link]("Enter another number:");
double num2 = [Link]();
[Link]("Enter the operator:");
op = [Link]().charAt(0);
if( op == '*' ) answer = num1 * num2;
else if( op == '/' ) answer = num1 / num2;
else if( op == '%' ) answer = num1 % num2;
else if( op == '+' ) answer = num1 + num2;
else if( op == '-' ) answer = num1 - num2;
else [Link]("Invalid operator");
[Link]("The result is: %,.3f", answer);
}
}

The charAt() method returns the character at the specified index in a


string. The index of the first character is 0, the second character is 1, and
so on. It is useful when you want a user to enter a single character from
the keyboard. The .charAt(0) method returns the first character in a
string.

COMPUTER PROGRAMMING 2 7
Sample Output:

If-else if Statements with the String Data Type


import [Link];

public class NameChecker {


public static void main(String[] args) {
Scanner scan = new Scanner([Link]);
String name = "";
[Link]("Enter your name:");
name = [Link]();
if([Link]("Elvis"))
[Link]("You are the king of rock and roll");
else if([Link]("Michael Jackson"))
[Link]("You are the king of pop!");
else
[Link]("You are not the king");
}
}

Sample Output:

The .equals() method compares two strings, and returns true if


the strings are equal, and false if not.
The .equalsIgnoreCase() method compares two strings, ignoring
lower case and upper case differences.

Nesting If and If-else Statements


Statements in which a decision is contained inside either the if or else
clause of another decision are nested if statements. These are
particularly useful when two or more conditions must be met before
some action is taken.
if(itemsSold >= 3)
if(totalValue >= 1000)
bonus = 50;
else
bonus = 25;
else
bonus = 10;

COMPUTER PROGRAMMING 2 8
Switch Statement

An alternative in using the series of nested if statements is to


use the switch statement. The switch statement is useful when you
need to test a single variable against a series of integral type (such
as exact integer including int, byte, and short types, character, or string
values.
The switch statement uses four keywords:
• switch starts the statement and is followed immediately by a test
expression enclosed in parentheses.
• case is followed by one of the possible values for the test
expression and a colon. The value of the test expression is
compared with the values of each case.
• break (optional) terminates a switch statement at the end of each
case. When Java reaches a break keyword, it breaks out of the
switch block.
• default (optional) is used to specify some code to run if the test
variable does not match any case.

Switch Statement with the char Data Type


import [Link];

public class SymbolChecker {


public static void main(String[] args) {
Scanner scan = new Scanner([Link]);
[Link]("Input a character");
char symbol = [Link]().charAt(0);
switch(symbol){
case '@': [Link]("At sign"); break;
case '&': [Link]("Ampersand"); break;
case 'a': [Link]("Lowercase a"); break;
default: [Link]("Not found");
}
}
}

Sample Output:

COMPUTER PROGRAMMING 2 9
Switch Statement with the int Data Type
After each case, include the keyword break. If not included, the code
will "fall through" and execute each case until break is encountered.
import [Link];

public class SalesWinner {


public static void main(String[] args) {
Scanner scan = new Scanner([Link]);
[Link]("How many memberships did you sell?");
int sales = [Link]();
switch(sales) {
case 6: [Link]("You win Php50000");
case 5: [Link]("You win iPhone");
case 4: [Link]("You win Laptop");
case 3: [Link]("You win Webcam");
case 2: [Link]("You win WiFi Dongle");
case 1: [Link]("You win Ballpen");
break;
default: [Link]("No Gift");
}
}
}

Sample Output:

COMPUTER PROGRAMMING 2 10
Switch Statement with the String Data Type
In Java SE 7 and later, you can use a String object in the switch
statement's expression.
import [Link];

public class DaySched {


public static void main(String[] args) {
Scanner scan = new Scanner([Link]);
[Link]("Enter a day:");
String day = [Link]();
switch(day) {
case "Monday":
[Link]("E-mail client 1"); break;
case "Tuesday":
[Link]("Design client's logo"); break;
case "Wednesday":
[Link]("Create PowerPoint slides"); break;
case "Thursday":
[Link]("Print reports"); break;
case "Friday":
[Link]("Meeting at 1 pm"); break;
case "Saturday":
case "Sunday":
[Link]("Weekend"); break;
default:
[Link]("Invalid day");
}
}
}

Sample Output:

Ternary Operator

The ternary operator (?:) in Java is a short-hand if-else statement.


The syntax of the ternary operator is:
testExpression ? trueResult : falseResult;
The testExpression is a Boolean expression that is evaluated as true
or false. If it is true, the entire conditional expression takes on the value
of the expression following the question mark (trueResult). If the
value of the testExpression is false, the entire expression takes on
the value of falseResult.
Example of an If-else statement:

A similar result is achieved using the ternary operator:

COMPUTER PROGRAMMING 2 11
Another example of an If-else statement:

A similar result is achieved using the ternary operator:

Lab Activity 3

To do:
1. Open the previous Java Project JavaExercises
2. Right click the src folder > New > Package
Package Name: [Link].surname3
3. Right click the package name > New > Class
4. Do the following sample programs in this lesson in each Class:
• NumberChecker
• Calculator
• NameChecker
• SymbolChecker
• SalesWinner
• DaySched
Note: Always check the public static void… option when
creating the class.

COMPUTER PROGRAMMING 2 12

Common questions

Powered by AI

Logical operators in Java, namely AND (&&), OR (||), and NOT (!), are used to combine multiple boolean expressions into one for more complex decision-making. They allow conditions to be interconnected, leading to more nuanced control over logic flow. For instance, in the condition if(honor && absent == 0), both honor must be true and absent must be zero for the body of the if statement to execute, such as printing 'You qualify for the scholarship.' This shows how logical operators can compound conditions to yield a single boolean outcome directing program execution .

Nested if statements allow fine-grained control over logic by establishing multi-level conditions where leading conditions filter subsequent ones. In granting a bonus, for example, if(itemsSold >= 3) and further check if(totalValue >= 1000), a higher-level sales target must be attained before considering additional criteria. This layered decision-making ensures only qualified situations satisfy all bonuses criteria. While effective, this complexity requires careful planning to maintain clarity and avoid inefficiencies or errors. Refactoring or replacing with switch statements can simplify when reading code or debugging becomes burdensome .

In a switch statement, the 'break' keyword prevents "fall-through" by terminating a case upon successful execution, ensuring that only the matched case's block executes. Without a break, execution will continue into subsequent cases regardless of their matching conditions, which can lead to unintended operations and bugs. For instance, omitting break within a reward allocation system after checking sales numbers might result in multiple rewards being assigned instead of the intended one. Thus, 'break' is crucial for maintaining control flow integrity and preventing logical errors .

The switch statement is more advantageous than a series of if-else statements when dealing with a variable that needs to be compared against a large number of discrete values. It offers cleaner syntax, improved readability, and potentially faster execution. Unlike if-else chains, the switch statement directly evaluates the target expression against expected values (cases). For example, in a program that assigns a response based on numerical input from 1 to 6, a switch statement efficiently lists each possible value followed by its outcome, avoiding the lengthy and repetitive syntax of equivalent if-else constructions . Use of switch in such set scenarios can also reduce errors and enhance code maintainability.

Relational operators in Java enable programmers to compare values and thus form the basis of decision-making processes within the program. These operators—such as greater than, less than, and equals to—are used to evaluate boolean expressions that steer the flow of execution depending on whether the conditions evaluate to true or false. For example, if(grade >= 88) checks if the grade is greater than or equal to 88 . Such evaluations are critical in implementing control structures like if-else statements that perform different actions based on the evaluated conditions.

In Java, a switch statement can use string objects, allowing for concise handling of various string comparisons against a target string variable. The structure involves initializing a switch block with the string variable followed by case statements for each string literal to check for equality. This can be advantageous for creating menu-driven applications or language parsers where a variable string could match one out of several fixed responses. An example is using switch to determine actions based on a day's name: switch(day) { case "Monday": System.out.println("Start work week"); ... This approach simplifies code by avoiding multiple if-else constructs .

A common pitfall when using the if statement in Java is accidentally placing a semicolon directly after the if condition, which nullifies the conditional control by terminating the if statement prematurely. This results in the subsequent code block being executed regardless of the condition's truthiness. For example, writing if(condition); { ... } will always execute the block as the semicolon denotes the end of the statement . This can be avoided by omitting semicolons after the if condition and instead using curly brackets to clearly define the block of code intended to be conditional.

Nested if-else statements can complicate program logic by creating deeper, harder-to-follow branches of decision-making, potentially leading to errors or making the code difficult to maintain and debug. As more conditions are nested, the readability decreases, and the cognitive load on the programmer increases. To manage this complexity, it's advisable to refactor the code by isolating complex conditions into separate functions, using descriptive naming conventions, or employing data structures like switch statements or polymorphism where applicable. This approach not only clarifies logic but also reduces nested depth, promoting better code quality .

The ternary operator provides a concise method for conditional assignment by encapsulating if-else logic into a single line of code. It is especially beneficial for simplifying code, reducing verbosity, and enhancing readability. Using the syntax (condition ? trueResult : falseResult), it evaluates a condition and assigns one of two possible values based on the condition's boolean outcome. For instance, for assigning a bonus based on sales, the ternary operator could replace a more verbose if-else structure: bonus = (sales >= target) ? highBonus : lowBonus; This straightforward mapping of conditions to variable assignments minimizes code deviation and focuses on core logic .

The Scanner class in Java is pivotal for reading user input from various input sources like keybords, files, etc. It simplifies the process of capturing and processing input data. For instance, to obtain an integer input from the user, Scanner scan = new Scanner(System.in); followed by int value = scan.nextInt(); is used. The importance of Scanner lies in its versatility and ease of use within interactive console applications, enabling programs to dynamically respond to user commands and inputs, thus allow practical user interaction .

You might also like