SlideShare a Scribd company logo
1 of 32
Chapter 3
Decision and Repetition Statements
1
Outline
• Overview of Java statements
• If statement
• Switch statement
• While, Do while loop
• For loop
2
Overview of Java statements
• In programming, a statement is an instruction to
do something.
• It controls the sequence of execution of a
program.
• In Java, a statement is terminated with a
semicolon and multiple statements can be
written on a single line.
Example: x = y + 1; z = y + 2;
• In Java, an empty statement is legal and does
nothing:
Example: ;
3
Cont…
• You can have a block of statements enclosed
between braces.
• If the value of expression is true, all the
statements enclosed in the block will be
executed.
• Without the braces, the code no longer has a
statement block
4
5-5
The if Statement
• The if statement has the following syntax:
if ( condition )
statement;
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
5-6
Logic of an if statement
condition
evaluated
statement
true
false
5-7
Logic of an if-else statement
condition
evaluated
statement1
true false
statement2
5-8
Boolean Expressions
• A condition often uses one of Java's equality
operators or relational operators, which all
return boolean results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
5-9
The if Statement
• An example of an if statement:
if (sum > MAX)
delta = sum - MAX;
System.out.println ("The sum is " + sum);
• First the condition is evaluated -- the value of sum is either greater
than the value of MAX, or it is not
• If the condition is true, the assignment statement is executed -- if it
isn’t, it is skipped.
• Either way, the call to println is executed next
Example
if (age < 0) output=“error”;
else if(age<=8) output=“too young”;
else if(age<=17) output=“ok”;
else if(age<=24) output=“too old”;
else output=“really really old”;
if(age < 0) output=“error”;
if(age<=8) output=“too young”;
if(age<=17) output=“ok”;
if(age<=24) output=“too old”;
else output=“really really old”;
Nested approach
Note: indentation is not
needed, its there for program
readability
Alternate approach – what is
Wrong with this code?
If you are 16, what
will output be?
We could solve this problem by reordering the
if statements in the opposite order, but the
new code would be inefficient – why? 10
The Switch Statement
• An alternate approach to using the nested if-else
structure is an instruction called switch
• We will use the switch statement if we are testing
a single variable against a list of values
• Structure:
– switch (variable)
{
case val1 : statement1;
case val2 : statement2;
case val3 : statement3;
…
case vallast : statementlast;
default : defaultstatement;
}
Compare variable with val1, val2,
… and pick which statement to
execute based on which value the
variable matches
11
Switch Example
switch (grade)
{
case ‘A’ :
comment = "gold star";
break;
case ‘B’ :
comment = "silver star";
break;
case ‘C’ :
comment = "bronze star";
break;
case ‘D’ :
comment = "no star";
break;
case ‘F’ :
comment = "demerit";
break;
default :
comment = "error, illegal letter grade! ";
}
In this example, comment is a
String which is assigned a value
based on the student’s letter grade
default is used as an error
checking mechanism here – if
reached, then the grade is an
illegal grade
NOTE: the word break is used
to exit the switch statement,
default is used as a final else
clause for the switch
12
Which Statement Should You Use?
• When it comes to
selection, you have
five possibilities:
– if statement
– if-else statement
– group of if
statements
– nested if-else
statement
– switch statement
• If there is only one action, then use
the if statement
• If two actions, one if the condition
is true, one if the condition is false,
then use the if-else statement
• If you have a series of possibilities,
which should you use?
– Switch statement if the possibility is
based on a single variable and the
variable is an integral data type
(integer, character or a user defined
type that is ordinal)
– Otherwise, use the nested if-else
statement
13
Repetition
• What happens if we want to do some action multiple
times?
– For instance, we want to count the number of times it takes when
rolling a 6-sided die until we roll a 6
• We write a program that rolls the 6-sided die once and outputs the
result, and then we could run the program over and over until we get a
6, but this is both tiresome and requires that the user count the number
of times we ran the program
– The better approach is to use a repetition statement which would
keep running the same random number instruction over and over
until it it a 6, so we will use a repetition control statement
– There are three forms of repetition statements in Java:
• While loops
• Do loops
• For loops
14
The While Statement
• The while statement evaluates a
condition
– if that condition is true, the body of the
while statement is executed and the
process is repeated
– If the condition is false, the rest of the
statement is skipped and control
continues with the next instruction after
the while statement
while ( condition )
statement;
while is a
reserved word
If the condition is true, the statement is executed.
Then the condition is evaluated again.
statement
true
condition
evaluated
false
15
Example
import java.util.Random;
public class SixRoller {
public static void main(String[] args) {
int count=1, die;
Random g = new Random();
die=g.nextInt(6)+1;
System.out.println("The first roll is a " + die);
while(die!=6) {
die=g.nextInt(6)+1;
count++;
System.out.println("The next roll is a " + die);
}
System.out.println("It took " + count + " rolls to get a 6");
}
}
16
Sum Example
Scanner in = new Scanner(System.in);
int value, sum;
…
sum = 0;
System.out.print(“Enter a positive integer, negative to quit: ”);
value = in.nextInt( );
while (value >= 0)
{
sum += value;
System.out.print(“Enter another positive integer, negative to quit: ”);
value = in.nextInt( );
}
System.out.println("The sum of the numbers you entered is " + sum);
value < 0 is our
sentinel for the loop
Notice that we repeated these
Instructions – why?
Initialize sum before we enter the loop
17
Infinite Loops
• Careless (and even careful) programmers will write
infinite loops
• This is a major problem when using the while loop
– The basic idea behind the loop is to continue executing
while a condition is true
• If that condition is based on an input value, then the program
must input a new value during each iteration so that the user can
change the value to one that exits the loop
• Otherwise, the value never changes and the loop never stops!
• Exiting an infinite loop
– if you suspect that your program is caught in an infinite
loop, about your only recourse is to stop the program
• Press control-C on the keyboard
18
The do Loop
• The do loop is similar to the while loop
but is a post-test loop, the while loop is a
pre-test loop
• The Do loop starts with the reserved
word do followed by the loop body and
then the reserved word while and the
condition
– The difference is the flow of control – here,
the condition is not evaluated until after the
body of the loop executes
do
{
statement;
}
while ( condition )
Uses both
the do and
while
reserved
words
true
condition
evaluated
statement
false
19
While vs. Do
• The only difference between
these two statements is when
the condition is evaluated
– While: evaluated before
executing the loop body
– Do: evaluated after executing
the loop body
• If you want to automatically
execute the loop body at least
once, use the Do loop
• If you don’t want to do the body if
the condition is not true, use the
While loop
statement
true
condition
evaluated
false
true
condition
evaluated
statement
false
20
Using Loops to Verify Input
• Consider a situation where we want
the user to input one of a set of
values that constitute a legal input
• What if the user enters an illegal
input?
– Example: input a non-negative
integer and take the square root
– If x < 0, we would get a run-time error
when the sqrt operation is invoked!
• A solution to this problem is
to place the prompt and
input statements inside a
loop that only terminates
once the user has entered
the right value
– We will use a do statement for
this since we will want the
user to input the value at least
one time
System.out.print(“Enter a non-negative number ”);
x = in.nextInt( );
y = Math.sqrt((double) x);
do
{
System.out.print(“Enter a non-negative number ”);
x = in.nextInt( );
} while (x < 0);
y = Math.sqrt((double) x);
21
Block Statements
• Several statements can be grouped together
into a block statement delimited by braces
• A block statement can be used wherever a
statement is called for in the Java syntax rules
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
22
5-23
Block Statements
• In an if-else statement, the if portion, or the
else portion, or both, could be block statements
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
else
{
System.out.println ("Total: " + total);
current = total*2;
}
5-24
Comparing Characters
• In Unicode, the digit characters (0-9) are contiguous
and in order
• Likewise, the uppercase letters (A-Z) and lowercase
letters (a-z) are contiguous and in order
Characters Unicode Values
0 – 9 48 through 57
A – Z 65 through 90
a – z 97 through 122
5-25
Comparing Strings
• Remember that in Java a character string is an
object
• The equals method can be called with strings
to determine if two strings contain exactly the
same characters in the same order
• The equals method returns a boolean result
if (name1.equals(name2))
System.out.println ("Same name");
5-26
Comparing Strings
• We cannot use the relational operators to compare strings
• The String class contains a method called compareTo
to determine if one string comes before another
• A call to name1.compareTo(name2)
– returns zero if name1 and name2 are equal (contain the same
characters)
– returns a negative value if name1 is less than name2
– returns a positive value if name1 is greater than name2
5-27
Comparing Strings
if (name1.compareTo(name2) < 0)
System.out.println (name1 + "comes first");
else
if (name1.compareTo(name2) == 0)
System.out.println ("Same name");
else
System.out.println (name2 + "comes first");
• Because comparing characters and strings is based on a character
set, it is called a lexicographic ordering
5-28
Comparing Objects
• The == operator can be applied to objects – it returns
true if the two references are aliases of each other
• The equals method is defined for all objects, but
unless we redefine it when we write a class, it has the
same semantics as the == operator
• It has been redefined in the String class to compare
the characters in the two strings
• When you write a class, you can redefine the equals
method to return true under whatever conditions are
appropriate
5-29
== vs. equals
• What is printed?
public static void main(String [] args)
{
GregorianCalendar today1 = new GregorianCalendar();
GregorianCalendar today2 = new GregorianCalendar();
GregorianCalendar todayCopy = today1;
System.out.println("today1 == today2: " +
(today1 == today2));
System.out.println("today1 == todayCopy: " +
(today1 == todayCopy));
System.out.println("todayCopy == today2: " +
(todayCopy == today2));
System.out.println("today1.equals(today2): " +
today1.equals(today2));
System.out.println("today1.equals(todayCopy): " +
today1.equals(todayCopy));
System.out.println("todayCopy.equals(today2): " +
todayCopy.equals(today2));
}
for ( int counter = 1; counter <= 10; counter++ )
Initial value
of control variable
Increment
of control variable
Control variable
name
Final value
of control variable
for
keyword
Loop-continuation condition
Components of a typical for structure header.
for Loop
31
The for Repetition Structure (cont.)
for ( expression1; expression2; expression3
)
statement;
can usually be rewritten as:
expression1;
while ( expression2 ) {
statement;
expression3;
}
32
Examples Using the for Structure
• Varying control variable in for structure
– Vary control variable from 1 to 100 in increments
of 1
• for ( int i = 1; i <= 100; i++ )
– Vary control variable from 100 to 1 in decrements
of –1
• for ( int i = 100; i >= 1; i-- )
– Vary control variable from 7 to 77 in steps of 7
• for ( int i = 7; i <= 77; i += 7 )

More Related Content

What's hot

Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual BasicTushar Jain
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision ControlJayfee Ramos
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in javaAtul Sehdev
 
Conditional statements
Conditional statementsConditional statements
Conditional statementscherrybear2014
 
Control Structures
Control StructuresControl Structures
Control StructuresGhaffar Khan
 
Control structure C++
Control structure C++Control structure C++
Control structure C++Anil Kumar
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statementsjyoti_lakhani
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
Control structures selection
Control structures   selectionControl structures   selection
Control structures selectionOnline
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 

What's hot (20)

Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual Basic
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in java
 
Conditional statements
Conditional statementsConditional statements
Conditional statements
 
C# conditional branching statement
C# conditional branching statementC# conditional branching statement
C# conditional branching statement
 
07 flow control
07   flow control07   flow control
07 flow control
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Control Structures
Control StructuresControl Structures
Control Structures
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statements
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
M C6java5
M C6java5M C6java5
M C6java5
 
Control structures selection
Control structures   selectionControl structures   selection
Control structures selection
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
 
Java control flow statements
Java control flow statementsJava control flow statements
Java control flow statements
 
Operators in java
Operators in javaOperators in java
Operators in java
 

Similar to Java chapter 3

C Programming - Decision making, Looping
C  Programming - Decision making, LoopingC  Programming - Decision making, Looping
C Programming - Decision making, LoopingMURALIDHAR R
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loopsManzoor ALam
 
Java learning
Java learningJava learning
Java learningmoew3
 
Lect3-C--EEB.pptx
Lect3-C--EEB.pptxLect3-C--EEB.pptx
Lect3-C--EEB.pptxKIJAMALEGI
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while LoopJayBhavsar68
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structuresayshasafdarwaada
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Blue Elephant Consulting
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
Programming in Java: Control Flow
Programming in Java: Control FlowProgramming in Java: Control Flow
Programming in Java: Control FlowMartin Chapman
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3Isham Rashik
 
Chapter 13.1.5
Chapter 13.1.5Chapter 13.1.5
Chapter 13.1.5patcha535
 
Conditional statements & Loops
Conditional statements & LoopsConditional statements & Loops
Conditional statements & Loopssaifullahbhatti99
 

Similar to Java chapter 3 (20)

C Programming - Decision making, Looping
C  Programming - Decision making, LoopingC  Programming - Decision making, Looping
C Programming - Decision making, Looping
 
UNIT 2 PPT.pdf
UNIT 2 PPT.pdfUNIT 2 PPT.pdf
UNIT 2 PPT.pdf
 
M C6java6
M C6java6M C6java6
M C6java6
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 
Java learning
Java learningJava learning
Java learning
 
Lect3-C--EEB.pptx
Lect3-C--EEB.pptxLect3-C--EEB.pptx
Lect3-C--EEB.pptx
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structures
 
control structure
control structurecontrol structure
control structure
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Control structure
Control structureControl structure
Control structure
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Programming in Java: Control Flow
Programming in Java: Control FlowProgramming in Java: Control Flow
Programming in Java: Control Flow
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
 
Chapter 13.1.5
Chapter 13.1.5Chapter 13.1.5
Chapter 13.1.5
 
Conditional statements & Loops
Conditional statements & LoopsConditional statements & Loops
Conditional statements & Loops
 

More from Abdii Rashid

object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examplesAbdii Rashid
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examplesAbdii Rashid
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printAbdii Rashid
 
Chapter 1 introduction haramaya
Chapter 1 introduction haramayaChapter 1 introduction haramaya
Chapter 1 introduction haramayaAbdii Rashid
 

More from Abdii Rashid (8)

Java chapter 7
Java chapter 7Java chapter 7
Java chapter 7
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java chapter 4
Java chapter 4Java chapter 4
Java chapter 4
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for print
 
Chapter 7 graphs
Chapter 7 graphsChapter 7 graphs
Chapter 7 graphs
 
Chapter 1 introduction haramaya
Chapter 1 introduction haramayaChapter 1 introduction haramaya
Chapter 1 introduction haramaya
 

Recently uploaded

Green Marketing Strategies and Challenges
Green Marketing Strategies and ChallengesGreen Marketing Strategies and Challenges
Green Marketing Strategies and ChallengesDr. Salem Baidas
 
Joint GBIF Biodiversa+ symposium in Helsinki on 2024-04-16
Joint GBIF Biodiversa+ symposium in  Helsinki on 2024-04-16Joint GBIF Biodiversa+ symposium in  Helsinki on 2024-04-16
Joint GBIF Biodiversa+ symposium in Helsinki on 2024-04-16Dag Endresen
 
Air pollution soli pollution water pollution noise pollution land pollution
Air pollution soli pollution water pollution noise pollution land pollutionAir pollution soli pollution water pollution noise pollution land pollution
Air pollution soli pollution water pollution noise pollution land pollutionrgxv72jrgc
 
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...Delhi Escorts
 
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一F dds
 
Poly-film-Prefab cover agricultural greenhouse-polyhouse structure.pptx
Poly-film-Prefab cover agricultural greenhouse-polyhouse structure.pptxPoly-film-Prefab cover agricultural greenhouse-polyhouse structure.pptx
Poly-film-Prefab cover agricultural greenhouse-polyhouse structure.pptxAgrodome projects LLP
 
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full NightCall Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Nightssuser7cb4ff
 
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service NashikRussian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashikranjana rawat
 
Dwarka Call Girls 9643097474 Phone Number 24x7 Best Services
Dwarka Call Girls 9643097474 Phone Number 24x7 Best ServicesDwarka Call Girls 9643097474 Phone Number 24x7 Best Services
Dwarka Call Girls 9643097474 Phone Number 24x7 Best Servicesnajka9823
 
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhidelih Escorts
 
(RIYA) Kalyani Nagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(RIYA) Kalyani Nagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(RIYA) Kalyani Nagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(RIYA) Kalyani Nagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
See How do animals kill their prey for food
See How do animals kill their prey for foodSee How do animals kill their prey for food
See How do animals kill their prey for fooddrsk203
 
VIP Kolkata Call Girl Kalighat 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kalighat 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kalighat 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kalighat 👉 8250192130 Available With Roomdivyansh0kumar0
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012sapnasaifi408
 

Recently uploaded (20)

Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
 
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
 
Green Marketing Strategies and Challenges
Green Marketing Strategies and ChallengesGreen Marketing Strategies and Challenges
Green Marketing Strategies and Challenges
 
Joint GBIF Biodiversa+ symposium in Helsinki on 2024-04-16
Joint GBIF Biodiversa+ symposium in  Helsinki on 2024-04-16Joint GBIF Biodiversa+ symposium in  Helsinki on 2024-04-16
Joint GBIF Biodiversa+ symposium in Helsinki on 2024-04-16
 
Air pollution soli pollution water pollution noise pollution land pollution
Air pollution soli pollution water pollution noise pollution land pollutionAir pollution soli pollution water pollution noise pollution land pollution
Air pollution soli pollution water pollution noise pollution land pollution
 
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
 
Gandhi Nagar (Delhi) 9953330565 Escorts, Call Girls Services
Gandhi Nagar (Delhi) 9953330565 Escorts, Call Girls ServicesGandhi Nagar (Delhi) 9953330565 Escorts, Call Girls Services
Gandhi Nagar (Delhi) 9953330565 Escorts, Call Girls Services
 
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
 
Green Banking
Green Banking Green Banking
Green Banking
 
Poly-film-Prefab cover agricultural greenhouse-polyhouse structure.pptx
Poly-film-Prefab cover agricultural greenhouse-polyhouse structure.pptxPoly-film-Prefab cover agricultural greenhouse-polyhouse structure.pptx
Poly-film-Prefab cover agricultural greenhouse-polyhouse structure.pptx
 
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full NightCall Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
 
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service NashikRussian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
 
young call girls in Janakpuri🔝 9953056974 🔝 escort Service
young call girls in Janakpuri🔝 9953056974 🔝 escort Serviceyoung call girls in Janakpuri🔝 9953056974 🔝 escort Service
young call girls in Janakpuri🔝 9953056974 🔝 escort Service
 
Dwarka Call Girls 9643097474 Phone Number 24x7 Best Services
Dwarka Call Girls 9643097474 Phone Number 24x7 Best ServicesDwarka Call Girls 9643097474 Phone Number 24x7 Best Services
Dwarka Call Girls 9643097474 Phone Number 24x7 Best Services
 
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
 
(RIYA) Kalyani Nagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(RIYA) Kalyani Nagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(RIYA) Kalyani Nagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(RIYA) Kalyani Nagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
See How do animals kill their prey for food
See How do animals kill their prey for foodSee How do animals kill their prey for food
See How do animals kill their prey for food
 
VIP Kolkata Call Girl Kalighat 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kalighat 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kalighat 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kalighat 👉 8250192130 Available With Room
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Call Girls In R.K. Puram 9953056974 Escorts ServiCe In Delhi Ncr
Call Girls In R.K. Puram 9953056974 Escorts ServiCe In Delhi NcrCall Girls In R.K. Puram 9953056974 Escorts ServiCe In Delhi Ncr
Call Girls In R.K. Puram 9953056974 Escorts ServiCe In Delhi Ncr
 

Java chapter 3

  • 1. Chapter 3 Decision and Repetition Statements 1
  • 2. Outline • Overview of Java statements • If statement • Switch statement • While, Do while loop • For loop 2
  • 3. Overview of Java statements • In programming, a statement is an instruction to do something. • It controls the sequence of execution of a program. • In Java, a statement is terminated with a semicolon and multiple statements can be written on a single line. Example: x = y + 1; z = y + 2; • In Java, an empty statement is legal and does nothing: Example: ; 3
  • 4. Cont… • You can have a block of statements enclosed between braces. • If the value of expression is true, all the statements enclosed in the block will be executed. • Without the braces, the code no longer has a statement block 4
  • 5. 5-5 The if Statement • The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.
  • 6. 5-6 Logic of an if statement condition evaluated statement true false
  • 7. 5-7 Logic of an if-else statement condition evaluated statement1 true false statement2
  • 8. 5-8 Boolean Expressions • A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to
  • 9. 5-9 The if Statement • An example of an if statement: if (sum > MAX) delta = sum - MAX; System.out.println ("The sum is " + sum); • First the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not • If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped. • Either way, the call to println is executed next
  • 10. Example if (age < 0) output=“error”; else if(age<=8) output=“too young”; else if(age<=17) output=“ok”; else if(age<=24) output=“too old”; else output=“really really old”; if(age < 0) output=“error”; if(age<=8) output=“too young”; if(age<=17) output=“ok”; if(age<=24) output=“too old”; else output=“really really old”; Nested approach Note: indentation is not needed, its there for program readability Alternate approach – what is Wrong with this code? If you are 16, what will output be? We could solve this problem by reordering the if statements in the opposite order, but the new code would be inefficient – why? 10
  • 11. The Switch Statement • An alternate approach to using the nested if-else structure is an instruction called switch • We will use the switch statement if we are testing a single variable against a list of values • Structure: – switch (variable) { case val1 : statement1; case val2 : statement2; case val3 : statement3; … case vallast : statementlast; default : defaultstatement; } Compare variable with val1, val2, … and pick which statement to execute based on which value the variable matches 11
  • 12. Switch Example switch (grade) { case ‘A’ : comment = "gold star"; break; case ‘B’ : comment = "silver star"; break; case ‘C’ : comment = "bronze star"; break; case ‘D’ : comment = "no star"; break; case ‘F’ : comment = "demerit"; break; default : comment = "error, illegal letter grade! "; } In this example, comment is a String which is assigned a value based on the student’s letter grade default is used as an error checking mechanism here – if reached, then the grade is an illegal grade NOTE: the word break is used to exit the switch statement, default is used as a final else clause for the switch 12
  • 13. Which Statement Should You Use? • When it comes to selection, you have five possibilities: – if statement – if-else statement – group of if statements – nested if-else statement – switch statement • If there is only one action, then use the if statement • If two actions, one if the condition is true, one if the condition is false, then use the if-else statement • If you have a series of possibilities, which should you use? – Switch statement if the possibility is based on a single variable and the variable is an integral data type (integer, character or a user defined type that is ordinal) – Otherwise, use the nested if-else statement 13
  • 14. Repetition • What happens if we want to do some action multiple times? – For instance, we want to count the number of times it takes when rolling a 6-sided die until we roll a 6 • We write a program that rolls the 6-sided die once and outputs the result, and then we could run the program over and over until we get a 6, but this is both tiresome and requires that the user count the number of times we ran the program – The better approach is to use a repetition statement which would keep running the same random number instruction over and over until it it a 6, so we will use a repetition control statement – There are three forms of repetition statements in Java: • While loops • Do loops • For loops 14
  • 15. The While Statement • The while statement evaluates a condition – if that condition is true, the body of the while statement is executed and the process is repeated – If the condition is false, the rest of the statement is skipped and control continues with the next instruction after the while statement while ( condition ) statement; while is a reserved word If the condition is true, the statement is executed. Then the condition is evaluated again. statement true condition evaluated false 15
  • 16. Example import java.util.Random; public class SixRoller { public static void main(String[] args) { int count=1, die; Random g = new Random(); die=g.nextInt(6)+1; System.out.println("The first roll is a " + die); while(die!=6) { die=g.nextInt(6)+1; count++; System.out.println("The next roll is a " + die); } System.out.println("It took " + count + " rolls to get a 6"); } } 16
  • 17. Sum Example Scanner in = new Scanner(System.in); int value, sum; … sum = 0; System.out.print(“Enter a positive integer, negative to quit: ”); value = in.nextInt( ); while (value >= 0) { sum += value; System.out.print(“Enter another positive integer, negative to quit: ”); value = in.nextInt( ); } System.out.println("The sum of the numbers you entered is " + sum); value < 0 is our sentinel for the loop Notice that we repeated these Instructions – why? Initialize sum before we enter the loop 17
  • 18. Infinite Loops • Careless (and even careful) programmers will write infinite loops • This is a major problem when using the while loop – The basic idea behind the loop is to continue executing while a condition is true • If that condition is based on an input value, then the program must input a new value during each iteration so that the user can change the value to one that exits the loop • Otherwise, the value never changes and the loop never stops! • Exiting an infinite loop – if you suspect that your program is caught in an infinite loop, about your only recourse is to stop the program • Press control-C on the keyboard 18
  • 19. The do Loop • The do loop is similar to the while loop but is a post-test loop, the while loop is a pre-test loop • The Do loop starts with the reserved word do followed by the loop body and then the reserved word while and the condition – The difference is the flow of control – here, the condition is not evaluated until after the body of the loop executes do { statement; } while ( condition ) Uses both the do and while reserved words true condition evaluated statement false 19
  • 20. While vs. Do • The only difference between these two statements is when the condition is evaluated – While: evaluated before executing the loop body – Do: evaluated after executing the loop body • If you want to automatically execute the loop body at least once, use the Do loop • If you don’t want to do the body if the condition is not true, use the While loop statement true condition evaluated false true condition evaluated statement false 20
  • 21. Using Loops to Verify Input • Consider a situation where we want the user to input one of a set of values that constitute a legal input • What if the user enters an illegal input? – Example: input a non-negative integer and take the square root – If x < 0, we would get a run-time error when the sqrt operation is invoked! • A solution to this problem is to place the prompt and input statements inside a loop that only terminates once the user has entered the right value – We will use a do statement for this since we will want the user to input the value at least one time System.out.print(“Enter a non-negative number ”); x = in.nextInt( ); y = Math.sqrt((double) x); do { System.out.print(“Enter a non-negative number ”); x = in.nextInt( ); } while (x < 0); y = Math.sqrt((double) x); 21
  • 22. Block Statements • Several statements can be grouped together into a block statement delimited by braces • A block statement can be used wherever a statement is called for in the Java syntax rules if (total > MAX) { System.out.println ("Error!!"); errorCount++; } 22
  • 23. 5-23 Block Statements • In an if-else statement, the if portion, or the else portion, or both, could be block statements if (total > MAX) { System.out.println ("Error!!"); errorCount++; } else { System.out.println ("Total: " + total); current = total*2; }
  • 24. 5-24 Comparing Characters • In Unicode, the digit characters (0-9) are contiguous and in order • Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order Characters Unicode Values 0 – 9 48 through 57 A – Z 65 through 90 a – z 97 through 122
  • 25. 5-25 Comparing Strings • Remember that in Java a character string is an object • The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order • The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name");
  • 26. 5-26 Comparing Strings • We cannot use the relational operators to compare strings • The String class contains a method called compareTo to determine if one string comes before another • A call to name1.compareTo(name2) – returns zero if name1 and name2 are equal (contain the same characters) – returns a negative value if name1 is less than name2 – returns a positive value if name1 is greater than name2
  • 27. 5-27 Comparing Strings if (name1.compareTo(name2) < 0) System.out.println (name1 + "comes first"); else if (name1.compareTo(name2) == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first"); • Because comparing characters and strings is based on a character set, it is called a lexicographic ordering
  • 28. 5-28 Comparing Objects • The == operator can be applied to objects – it returns true if the two references are aliases of each other • The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator • It has been redefined in the String class to compare the characters in the two strings • When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate
  • 29. 5-29 == vs. equals • What is printed? public static void main(String [] args) { GregorianCalendar today1 = new GregorianCalendar(); GregorianCalendar today2 = new GregorianCalendar(); GregorianCalendar todayCopy = today1; System.out.println("today1 == today2: " + (today1 == today2)); System.out.println("today1 == todayCopy: " + (today1 == todayCopy)); System.out.println("todayCopy == today2: " + (todayCopy == today2)); System.out.println("today1.equals(today2): " + today1.equals(today2)); System.out.println("today1.equals(todayCopy): " + today1.equals(todayCopy)); System.out.println("todayCopy.equals(today2): " + todayCopy.equals(today2)); }
  • 30. for ( int counter = 1; counter <= 10; counter++ ) Initial value of control variable Increment of control variable Control variable name Final value of control variable for keyword Loop-continuation condition Components of a typical for structure header. for Loop
  • 31. 31 The for Repetition Structure (cont.) for ( expression1; expression2; expression3 ) statement; can usually be rewritten as: expression1; while ( expression2 ) { statement; expression3; }
  • 32. 32 Examples Using the for Structure • Varying control variable in for structure – Vary control variable from 1 to 100 in increments of 1 • for ( int i = 1; i <= 100; i++ ) – Vary control variable from 100 to 1 in decrements of –1 • for ( int i = 100; i >= 1; i-- ) – Vary control variable from 7 to 77 in steps of 7 • for ( int i = 7; i <= 77; i += 7 )