0% found this document useful (0 votes)
7 views

ITC C106 Lecture - Decision Control Structures

Uploaded by

Isaac esparrago
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

ITC C106 Lecture - Decision Control Structures

Uploaded by

Isaac esparrago
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

ITC C106 – Computer

Programming II

Module 1
Java Decision Structures
Prepared by: A. C. Valderama – CSE- IT
Dept.
Module Objectives
• Review and recognize the concept and code
programs using decision control structures (if,
if else, if else if, switch) which allows selection
of specific sections of code to be executed.
• Recall the use of relational and logical
operators and flags.
• Induce coding with order of operator
precedence, numeric ranges, String objects
comparison and the use of the DecimalFormat
class
Prepared by: A. C. Valderama – CSE- IT
Dept.
Content Outline

1. Relational Operators 9. Logical operators


2. if statements and 10. Order of precedence
boolean expressions 11. Checking numeric
3. Programming style and ranges
if statements 12. Comparing String
4. Block if statements objects
5. Flags 13. The conditional
6. if-else statements operator
7. Nested if statements 14. The switch statement
8. if-else-if statements 15. The case statement

Prepared by: A. C. Valderama – CSE- IT


Dept.
The if Statement
• The if statement decides whether a section
of code executes or not.
• The if statement uses a boolean value to
decide whether the next statement or block of
statements executes.

if (boolean expression is true)


execute next statement.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Flowcharts
• If statements can be modeled as a
flowchart.

if (hasTikTok) Do you have Yes


displayUsername(); a Tiktok
acct.?
Display username.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Flowcharts
• A block if statement may be modeled as:

if (hasTiktok)
{ Do you
have a Yes
displayUsername();
postVideo(); Tiktok
monitorComments(); acct.?
Display username.
}
Post a 30 sec. video.
Note the use of curly
braces to block several Monitor comments.
statements together.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Relational Operators
• In most cases, the boolean expression,
used by the if statement, uses relational operators.

Relational Operators Meaning


> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
== is equal to
!= is not equal to

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Boolean Expressions
• A boolean expression is any variable or
calculation that results in a true or false condition.
Expression Meaning
x>y Is x greater than y?
x<y Is x less than y?
x >= y Is x greater than or equal to y?
x <= y Is x less than or equal to y.
x == y Is x equal to y?
x != y Is x not equal to y?

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
if Statements and Boolean Expressions

1 import javax.swing.JOptionPane;
2
3 public class IfNumbers {
4 public static void main(String[] args) {
5 String input;
6 int number;
7
8 input = JOptionPane.showInputDialog(“Enter a number:”);
9 number = Integer.parseInt(input);
10
11 if(number > 10)
12 JOptionPane.showMessageDialog(null, “The number is greater than 10.”);
13 if(number < 10)
14 JOptionPane.showMessageDialog(null, “The number is less than 10.”);
15 if(number == 10)
16 JOptionPane.showMessageDialog(null, “The number is 10”);
17
18 System.exit(0);
19 } Prepared by: A. C. Valderama – CSE- IT
20 } Dept.
Table of contents
if Statements and Boolean Expressions

1 import javax.swing.JOptionPane;
2
3 public class IfNumbers {
4 public static void main(String[] args) {
5 String input;
6 int number;
7
8 input = JOptionPane.showInputDialog(“Enter a number:”);
9 number = Integer.parseInt(input);
10
11 if(number > 10)
12 JOptionPane.showMessageDialog(null, “The number is greater than
10.”);
13 if(number < 10)
14 JOptionPane.showMessageDialog(null, “The number is less than 10.”);
15 if(number == 10)
16 JOptionPane.showMessageDialog(null, “The number is 10”);
17
18 System.exit(0); Prepared by: A. C. Valderama – CSE- IT
19 } Dept.
Table of contents
if Statements and Boolean Expressions

1 import javax.swing.JOptionPane;
2
3 public class IfNumbers {
4 public static void main(String[] args) {
5 String input;
6 int number;
7
8 input = JOptionPane.showInputDialog(“Enter a number:”);
9 number = Integer.parseInt(input);
10
11 if(number > 10)
12 JOptionPane.showMessageDialog(null, “The number is greater than 10.”);
13 if(number < 10)
14 JOptionPane.showMessageDialog(null, “The number is less than 10.”);
15 if(number == 10)
16 JOptionPane.showMessageDialog(null, “The number is 10”);
17
18 System.exit(0);
19 } Prepared by: A. C. Valderama – CSE- IT
20 } Dept.
Table of contents
Programming Style and
if Statements

• An if statement can span more than one line;


however, it is still one statement.
if (average > 95)
grade = ′A′;

is functionally equivalent to

if(average > 95) grade = ′A′;

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Programming Style and
if Statements
• Rules of thumb:
– The conditionally executed statement should be
on the line after the if condition.
– The conditionally executed statement should be
indented one level from the if condition.
– If an if statement does not have the block curly
braces, it is ended by the first semicolon
encountered after the if condition.
if (expression) No semicolon here.
statement; Semicolon ends statement here.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Block if Statements
• Conditionally executed statements can be grouped
into a block by using curly braces {} to enclose
them.
• If curly braces are used to group conditionally
executed statements, the if statement is ended
by the closing curly brace.

if (expression)
{
statement1;
statement2;
} Curly brace ends the statement.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Block if Statements
• Remember that when the curly braces are not used,
then only the next statement after the if condition
will be executed conditionally.

if (expression)
statement1; Only this statement is conditionally executed.

statement2;
statement3;

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Flags
• A flag is a boolean variable that monitors some
condition in a program.
• When a condition is true, the flag is set to true.
• The flag can be tested to see if the condition has
changed.
if (GWA > 95)
highScore = true;
• Later, this condition can be tested:
if (highScore)
System.out.println("That′s a high general weighted
average!");

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Comparing Characters
• Characters can be tested with relational operators.
• Characters are stored in memory using the Unicode
character format.
• Unicode is stored as a sixteen (16) bit number.
• Characters are ordinal, meaning they have an order in the
Unicode character set.
• Since characters are ordinal, they can be compared to each
other.

char c = ′A′;
if(c < ′Z′)
System.out.println("A is less than Z");

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
if-else Statements
• The if-else statement adds the ability to
conditionally execute code when the if
condition is false.

if (expression)
statementOrBlockIfTrue;
else
statementOrBlockIfFalse;

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
if-else Statement
Flowcharts

No Yes
Do you have a
Tiktok acct.?
Create one. Display username.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
if-else Statement

1 import javax.swing.JOptionPane;
2 public class Division {
3 public static void main(String[] args) {
4 double number1, number 2, quotient;
5 String input;
6 input = JOptionPane.showInputDialog(“Enter a number: “);
7 number1 = Double.parseDouble(input);
8
9 input = JOptionPane.showInputDialog(“Enter another number: “);
10 number 2 = Double.parseDouble(input);
11
12 if(number2 == 0) {
13 JOptionPane.showMessageDialog(null, “Division by 0 “ + “ is not possible!”);
14 }
15 else {
16 quotient = number1 / number2;
17 JOptionPane.showMessageDialog(null, “The quotient of “ + number1 + “ divided by “ + number2
+ “ is: “ + quotient);
18 }
19 } Prepared by: A. C. Valderama – CSE- IT
20 } Dept.
Table of contents
if-else Statement

1 import javax.swing.JOptionPane;
2 public class Division {
3 public static void main(String[] args) {
4 double number1, number 2, quotient;
5 String input;
6 input = JOptionPane.showInputDialog(“Enter a number: “);
7 number1 = Double.parseDouble(input);
8
9 input = JOptionPane.showInputDialog(“Enter another number: “);
10 number 2 = Double.parseDouble(input);
11
12 if(number2 == 0) {
13 JOptionPane.showMessageDialog(null, “Division by 0 “ + “ is not possible!”);
14 }
15 else {
16 quotient = number1 / number2;
17 JOptionPane.showMessageDialog(null, “The quotient of “ + number1 + “ divided by “ + number2
+ “ is: “ + quotient);
18 }
19 } Prepared by: A. C. Valderama – CSE- IT
20 } Dept.
Table of contents
Nested if Statements

• If an if statement appears inside another if


statement (single or block) it is called a nested
if statement.
• The nested if is executed only if the outer if
statement results in a true condition.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Nested if Statement Flowcharts

No Yes
Do you have a
Tiktok acct.?
Create one.
No Yes
Do you have
followers?

Share your acct. Display # of


in Facebook. followers.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Nested if Statements
if (hasTiktok)
{
if (hasFollowers)
{
displayNumFollowers();
}
else
{
sharePostInFb();
}
}
else
{
createAcct();
}

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
if-else Matching
• Curly brace use is not required if there is only
one statement to be conditionally executed.
• However, sometimes curly braces can help
make the program more readable.
• Additionally, proper indentation makes it
much easier to match up else statements with
their corresponding if statement.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Alignment and Nested if Statements
if (hasTiktok)
{
if (hasFollowers)
This if and else {
This if and else go together.
go together. displayNumFollowers();
}
else
{
sharePostInFb();
}
}
else
{
createAcct();
} – CSE- IT
Prepared by: A. C. Valderama
Dept.
Table of contents
Nested if Statements

import javax.swing.JOptionPane;
public class NestedIf {
public static void main(String[] args) {
String input;
double number;

input = JOptionPane.showInputDialog("Enter your mark:");


number = Double.parseDouble(input);

if(number < 50)


JOptionPane.showMessageDialog(null, "You failed!");
else {
if(number >= 50) {
if(number >= 80)
JOptionPane.showMessageDialog(null, "You passed with distinction!");
else
JOptionPane.showMessageDialog(null, "You passed!");
}
}
System.exit(0);
} Prepared by: A. C. Valderama – CSE- IT
} Dept.
Table of contents
Nested if Statements

import javax.swing.JOptionPane;
public class NestedIf {
public static void main(String[] args) {
String input;
double number;

input = JOptionPane.showInputDialog("Enter your mark:");


number = Double.parseDouble(input);

if(number < 50)


JOptionPane.showMessageDialog(null, "You failed!");
else {
if(number >= 50) {
if(number >= 80)
JOptionPane.showMessageDialog(null, "You passed with distinction!");
else
JOptionPane.showMessageDialog(null, "You passed!");
}
}
System.exit(0);
} Prepared by: A. C. Valderama – CSE- IT
} Dept.
Table of contents
Nested if Statements

import javax.swing.JOptionPane;
public class NestedIf {
public static void main(String[] args) {
String input;
double number;

input = JOptionPane.showInputDialog("Enter your mark:");


number = Double.parseDouble(input);

if(number < 50)


JOptionPane.showMessageDialog(null, "You failed!");
else {
if(number >= 50) {
if(number >= 80)
JOptionPane.showMessageDialog(null, "You passed with distinction!");
else
JOptionPane.showMessageDialog(null, "You passed!");
}
}
System.exit(0);
} Prepared by: A. C. Valderama – CSE- IT
} Dept.
Table of contents
if-else-if Statements
if (expression_1)
{
statement;
statement; If expression_1 is true these statements are
etc. executed, and the rest of the structure is ignored.
}
else if (expression_2)
{
statement;
statement; Otherwise, if expression_2 is true these statements are
etc. executed, and the rest of the structure is ignored.
}

Insert as many else if clauses as necessary

else
{
statement;
statement; These statements are executed if none of
etc. the expressions above are true.
}
Prepared by: A. C. Valderama – CSE- IT
Dept.
Table of contents
if-else-if Statements

• Nested if statements can become very


complex.
• The if-else-if statement makes certain
types of nested decision logic simpler to write.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
if-else-if Flowchart

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Logical Operators
• Java provides two binary logical operators
(&& and ||) that are used to combine boolean
expressions.
• Java also provides one unary (!) logical
operator to reverse the truth of a boolean
expression.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Logical Operators

Operator Meaning Effect


Connects two boolean expressions into one. Both
&& AND expressions must be true for the overall expression to
be true.
Connects two boolean expressions into one. One or
both expressions must be true for the overall
|| OR
expression to be true. It is only necessary for one to
be true, and it does not matter which one.
The ! operator reverses the truth of a boolean
expression. If it is applied to an expression that is
! NOT
true, the operator returns false. If it is applied to an
expression that is false, the operator returns true.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The && Operator
• The logical AND operator (&&) takes two operands that must
both be boolean expressions.
• The resulting combined expression is true if (and only if) both
operands are true.

Expression 1 Expression 2 Expression1 && Expression2


true false false
false true false
false false false
true true true

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
import javax.swing.JOptionPane;

public class Main


The && Operator
{
public static void main(String[] args)
{
String input;
double number;

input = JOptionPane.showInputDialog("Enter your mark:");


number = Double.parseDouble(input);

if(number < 50)


JOptionPane.showMessageDialog(null, "You failed!");

else
{
if(number >= 50 && number >= 80)
{
JOptionPane.showMessageDialog(null, "You passed with distinction!");
}
else
{
JOptionPane.showMessageDialog(null, "You passed!");
}
}
System.exit(0);
} Prepared by: A. C. Valderama – CSE- IT
} Dept.
Table of contents
The || Operator
• The logical OR operator (||) takes two operands that
must both be boolean expressions.
• The resulting combined expression is false if (and only
if) both operands are false.

Expression 1 Expression 2 Expression1 || Expression2


true false true
false true true
false false false
true true true

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The || Operator

if( salary >=30000 || yearsOnJob >= 2)


{
System.out.println(“You qualify for the loan!”);
}

else
{
System.out.println(“You do not qualify for the loan”);
}

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The ! Operator

• The ! operator performs a logical NOT operation.


• If an expression is true, !expression will be false.
if (!(temperature > 100))
System.out.println("Below the maximum temperature.");

• If temperature > 100 evaluates to false, then the output


statement will be run.

Expression 1 !Expression1
true false
false true

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Order of Precedence
• The ! operator has a higher order of
precedence than the && and || operators.
• The && and || operators have a lower
precedence than relational operators like <
and >.
• Parenthesis can be used to force the
precedence to be changed.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Order of Precedence
Order of
Operators Description
Precedence
1 (unary negation) ! Unary negation, logical NOT
2 */% Multiplication, Division, Modulus
3 +- Addition, Subtraction
Less-than, Greater-than, Less-than or
4 < > <= >=
equal to, Greater-than or equal to
5 == != Is equal to, Is not equal to
6 && Logical AND
7 || Logical NOT
= += -= Assignment and combined assignment
8
*= /= %= operators.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Checking numeric ranges
 When determining whether a number is
inside a range, it’s best to use the &&
operator.
Range 20 to 40

if ( x >= 20 && x <=40 )


System.out.println(x + “ is in the range”);

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Checking numeric ranges
 When determining whether a number is
outside a range, it’s best to use the ||
operator.
Outside range 20 to 40
if ( x < 20 || x > 40 )
System.out.println(x + “ is outside the range”);

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Comparing String Objects
• In most cases, you cannot use the relational
operators to compare two String objects.
• Reference variables contain the address of the
object they represent.
• Unless the references point to the same object,
the relational operators will not return true.
String name1 = “Andrea”; String name2 = “Andy”;

if (name1 == name2) This statement will be false

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Comparing String Objects
• In most cases, you cannot use the relational
operators to compare two String objects.
• Reference variables contain the address of the
object they represent.
• Unless the references point to the same object,
the relational operators will not return true.
String name1 = “Andrea”; String name2 = “Andrea”;

if (name1 == name2) This statement will be false as well

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Comparing String Objects
String name1 = “Andrea”; String name2 = “Andrea”;

if (name1 == name2) This statement will be false as well

name1 String Memory


“Andrea”
address of
String
object

Because name1 and name2 does not point to


the same object, they are not the same
Variable name1 String object
according to the relational operators

name2 String Memory


“Andrea”
address of
String
object

Variable name2 Another String object


Prepared by: A. C. Valderama – CSE- IT
Dept.
Table of contents
Comparing String Objects
String name1 = “Andrea”; String name2 = “Andrea”;

if (name1 == name2) This statement will be false as well

name1 String Memory


“Andrea”
address of
String
object

Because name1 and name2 does not point to


the same object, they are not the same
Variable name1 String object
according to the relational operators

name2 String Memory


“Andrea”
address of
String
object

Variable name2 Another String object


Prepared by: A. C. Valderama – CSE- IT
Dept.
Table of contents
Comparing String Objects
The equals method

String name1 = “Andrea”; String name2 = “Andrea”;

if (name1.equals(name2)) This statement will be true

if (name1.equals(“Andrea”)) This statement will be true

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Comparing String Objects
The equals method

String name1 = “Andrea”; String name2 = “Andrea”;

if (name1.equals(name2)) This statement will be true

if (name1.equals(“Andrea”)) This statement will be true

if (!name1.equals(“Andrea”)) This statement will be false

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Comparing String Objects
The compareTo method

if (name1.compareTo(name2) == 0)

The method returns an integer value that can be used in


the following manner:

If the value is 0, name1 will be equal to name2

If the value is negative, name1 will be smaller than name2

If the value is positive, name1 will be greater than name2

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Comparing String Objects
The compareTo method
if (name1.compareTo(name2) == 0)
{
System.out.print(“The names are the same”);
}

else if (name1.compareTo(name2) < 0)


{
System.out.print(name1 + “ is less than “ + name2);
}

else if (name1.compareTo(name2) > 0)


{
System.out.print(name1 + “ is greater than “ + name2);
}
Prepared by: A. C. Valderama – CSE- IT
Dept.
Table of contents
Comparing String Objects
The compareTo method

String name1 = M A R K

String name2 = M A R Y
The same The same The same K less
than Y
Thus, name1 is less than name2

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Comparing String Objects
The compareTo method

GREATER

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

LESS

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
Ignoring Case in String Comparisons
• In the String class the equals and
compareTo methods are case sensitive.
• In order to compare two String objects
that might have different case, use:
– equalsIgnoreCase, or
– compareToIgnoreCase
if (name1.compareToIgnoreCase(name2) == 0)
{
System.out.print(“The names are the same”);
}
Prepared by: A. C. Valderama – CSE- IT
Dept.
Table of contents
Variable Scope
• In Java, a local variable does not have to be
declared at the beginning of the method.
• The scope of a local variable begins at the point
it is declared and terminates at the end of the
method.
• When a program enters a section of code where
a variable has scope, that variable has come into
scope, which means the variable is visible to the
program.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The Conditional Operator
• The conditional operator is a ternary (three
operand) operator.
• You can use the conditional operator to write
a simple statement that works like an if-
else statement.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The Conditional Operator
• The format of the operators is:

BooleanExpression ? Value1 : Value2

• This forms a conditional expression.


• If BooleanExpression is true, the value of the
conditional expression is Value1.
• If BooleanExpression is false, the value of the
conditional expression is Value2.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The Conditional Operator
• Example:
number = x > y ? 10 : 5;
• This line is functionally equivalent to:
if(x > y)
number = 10;
else
number = 5;

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The Conditional Operator
• Consider the following statement:
System.out.println(“Your grade is: “ +
(score < 60 ? “Fail” : “Pass”));

• Converted to an if-else statement:


if(score < 60)
System.out.println(“Your grade is: Fail”);
else
System.out.println(“Your grade is: Pass”);

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The switch Statement
• The if-else statement allows you to make
true / false branches.
• The switch statement allows you to use an
ordinal value to determine how a program will
branch.
• The switch statement can evaluate an
integer type or character type variable and
make decisions based on the value.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The switch Statement
• The switch statement takes the form:
switch (SwitchExpression)
{
case CaseExpression:
// place one or more statements here
break;
case CaseExpression:
// place one or more statements here
break;

// case statements may be repeated


//as many times as necessary
default:
// place one or more statements here
}

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The switch Statement
• The switch statement takes an ordinal value (byte,
short, int, long, or char) as the SwitchExpression.

switch (SwitchExpression)
{

}

• The switch statement will evaluate the expression.


• If there is an associated case statement that matches that
value, program execution will be transferred to that case
statement.
Prepared by: A. C. Valderama – CSE- IT
Dept.
Table of contents
The switch Statement
• Each case statement will have a corresponding
CaseExpression that must be unique.

case CaseExpression:
// place one or more statements here
break;

• If the SwitchExpression matches the CaseExpression,


the Java statements between the colon and the
break statement will be executed.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The case Statement
• The break statement ends the case
statement.
• The break statement is optional.
• Without the break statements, the program
would execute all of the lines from the matching
case statement to the end of the block.
• The default section is optional and will be
executed if no CaseExpression matches the
SwitchExpression.

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
The case Statement
public static
Program void main(String[] args)
output:
{
Enter 1, 2 or 3: 2 [Enter]
int number;
You entered 2.
Scanner keyboard = new Scanner(System.in);

System.out.print(“Enter 1, 2 or 3: “);
number = keyboard.nextInt();

switch (number)
{
case 1:
System.out.println(“You entered 1.”);
break;
case 2:
System.out.println(“You entered 2.”);
break;
case 3:
System.out.println(“You entered 3.”);
break;
default:
System.out.println(“That’s not 1, 2 or 3!”);
}
} Prepared by: A. C. Valderama – CSE- IT
Dept.
Table of contents
The case Statement
public static void main(String[] args)
{
int number;
Program output:
Scanner keyboard = new Scanner(System.in); Enter 1, 2 or 3: 1 [Enter]
You entered 1.
System.out.print(“Enter 1, 2 or 3: “); You entered 2.
number = keyboard.nextInt(); You entered 3.
That’s not 1, 2 or 3!
switch (number)
{
case 1:
System.out.println(“You entered 1.”);
case 2:
System.out.println(“You entered 2.”);
case 3:
System.out.println(“You entered 3.”);
default:
System.out.println(“That’s not 1, 2 or 3!”);
}
}

Prepared by: A. C. Valderama – CSE- IT


Dept.
Table of contents
public static void main(String[] args)
{
String input;
char foodGrade;

Scanner keyboard = new Scanner(System.in);


Asks the user to
System.out.println(“Our pet food is available in three grades:“);
System.out.print(“A, B and C. Which do you want pricing for? ”);
select a grade of
pet food
input = keyboard.nextLine();
foodGrade = input.charAt(0); Stores the input as a character in variable foodGrade
switch (foodGrade)
{
case ‘a’: No break statement
case ‘A’:
System.out.println(“30 cents per gram”);
break;
case ‘b’: No break statement
case ‘B’:
System.out.println(“20 cents per gram”);
break;
case ‘c’: No break statement
case ‘C’:
System.out.println(“10 cents per gram”);
break;
default:
System.out.println(“Invalid choice”);
}
Prepared by: A. C. Valderama – CSE- IT
} Dept.
Table of contents
public static void main(String[] args)
{
String input;
char foodGrade;

Scanner keyboard = new Scanner(System.in);

System.out.println(“Our pet food is available in three grades:“);


System.out.print(“A, B and C. Which do you want pricing for? ”);

input = keyboard.nextLine(); Program output:


foodGrade = input.charAt(0); Our pet food is available in three grades:
switch (foodGrade)
A, B and C. Which do you want pricing for? a [Enter]
{ 30 cents per gram
case ‘a’:
case ‘A’:
System.out.println(“30 cents per gram”);
break;
case ‘b’:
case ‘B’:
System.out.println(“20 cents per gram”);
break;
case ‘c’:
case ‘C’:
System.out.println(“10 cents per gram”);
break;
default:
System.out.println(“Invalid choice”);
}
Prepared by: A. C. Valderama – CSE- IT
} Dept.
Table of contents
public static void main(String[] args)
{
String input;
char foodGrade;

Scanner keyboard = new Scanner(System.in);

System.out.println(“Our pet food is available in three grades:“);


System.out.print(“A, B and C. Which do you want pricing for? ”);

input = keyboard.nextLine(); Program output:


foodGrade = input.charAt(0); Our pet food is available in three grades:
switch (foodGrade)
A, B and C. Which do you want pricing for? B [Enter]
{ 20 cents per gram
case ‘a’:
case ‘A’:
System.out.println(“30 cents per gram”);
break;
case ‘b’:
case ‘B’:
System.out.println(“20 cents per gram”);
break;
case ‘c’:
case ‘C’:
System.out.println(“10 cents per gram”);
break;
default:
System.out.println(“Invalid choice”);
}
Prepared by: A. C. Valderama – CSE- IT
} Dept.
Table of contents
Reference:
• Adapted and edited from Java
Programming, Beaulieu College

Prepared by: A. C. Valderama – CSE- IT


Dept.
Thank you!

Prepared by: A. C. Valderama – CSE- IT


Dept.

You might also like