SlideShare a Scribd company logo
1 of 22
Chapter 5
Conditionals and
Loops: Part 5
• Java Software Solutions
• Foundations of Program
Design
• 9th Edition
John Lewis
William Loftus
Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Key
Concept
A loop allows a program to
execute a statement
multiple times.
Repetition Statements
• Repetition statements allow us to execute a
statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
while, do, and for loops
• The do and for loops are discussed in Chapter 6
The while
Statement
• A while statement has the following
syntax:
while ( condition
)
statement;
• If the condition is true, the
statement is executed
• Then the condition is evaluated
again, and if it is still true, the
statement is executed again
• The statement is executed
repeatedly until the condition
becomes false
Logic of a while Loop
statement
true
false
condition
evaluated
The while
Statement
• An example of a while statement:
• If the condition of a while loop is false
initially, the statement is never executed
• Therefore, the body of a while loop will
execute zero or more times
• int count = 1;
• while (count <= 5)
• {
• System.out.println(count);
• count++;
• }
Sentinel
Values
• Let's look at some examples
of loop processing
• A loop can be used to
maintain a running sum
• A sentinel value is a special
input value that represents
the end of input
• See Average.java
//********************************************************************
// Average.java Author: Lewis/Loftus
//
// Demonstrates the use of a while loop, a sentinel value, and a
// running sum.
//********************************************************************
import java.text.DecimalFormat;
import java.util.Scanner;
public class Average
{
//-----------------------------------------------------------------
// Computes the average of a set of values entered by the user.
// The running sum is printed as the numbers are entered.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int sum = 0, value, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
value = scan.nextInt();
continue
continue
while (value != 0) // sentinel value of 0 to terminate loop
{
count++;
sum += value;
System.out.println("The sum so far is " + sum);
System.out.print("Enter an integer (0 to quit): ");
value = scan.nextInt();
}
continue
continue
System.out.println();
if (count == 0)
System.out.println("No values were entered.");
else
{
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
}
continue
System.out.println();
if (count == 0)
System.out.println("No values were entered.");
else
{
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
}
Sample Run
Enter an integer (0 to quit): 25
The sum so far is 25
Enter an integer (0 to quit): 164
The sum so far is 189
Enter an integer (0 to quit): -14
The sum so far is 175
Enter an integer (0 to quit): 84
The sum so far is 259
Enter an integer (0 to quit): 12
The sum so far is 271
Enter an integer (0 to quit): -35
The sum so far is 236
Enter an integer (0 to quit): 0
The average is 39.333
Input
Validation
• A loop can also be used for
input validation, making a
program more robust
• It's generally a good idea to
verify that input is valid (in
whatever sense) when
possible
• See
WinPercentage.java
//********************************************************************
// WinPercentage.java Author: Lewis/Loftus
//
// Demonstrates the use of a while loop for input validation.
//********************************************************************
import java.text.NumberFormat;
import java.util.Scanner;
public class WinPercentage
{
//-----------------------------------------------------------------
// Computes the percentage of games won by a team.
//-----------------------------------------------------------------
public static void main(String[] args)
{
final int NUM_GAMES = 12;
int won;
double ratio;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of games won (0 to "
+ NUM_GAMES + "): ");
won = scan.nextInt();
continue
continue
while (won < 0 || won > NUM_GAMES)
{
System.out.print("Invalid input. Please reenter: ");
won = scan.nextInt();
}
ratio = (double)won / NUM_GAMES;
NumberFormat fmt = NumberFormat.getPercentInstance();
System.out.println();
System.out.println("Winning percentage: " + fmt.format(ratio));
}
}
continue
while (won < 0 || won > NUM_GAMES)
{
System.out.print("Invalid input. Please reenter: ");
won = scan.nextInt();
}
ratio = (double)won / NUM_GAMES;
NumberFormat fmt = NumberFormat.getPercentInstance();
System.out.println();
System.out.println("Winning percentage: " + fmt.format(ratio));
}
}
Sample Run
Enter the number of games won (0 to 12): -5
Invalid input. Please reenter: 13
Invalid input. Please reenter: 7
Winning percentage: 58%
Infinite
Loops
• The body of a while loop
eventually must make the
condition false
• If not, it is called an infinite
loop, which will execute until
the user interrupts the
program
• This is a common logical error
• You should always double
check the logic of a program
to ensure that your loops will
terminate normally
Infinite Loops
• An example of an infinite loop:
• This loop will continue executing until interrupted
(Control-C) or until an underflow error occurs
int count = 1;
while (count <= 25)
{
System.out.println(count);
count = count - 1;
}
Nested
Loops
• Similar to nested if
statements, loops can be
nested as well
• That is, the body of a loop can
contain another loop
• For each iteration of the outer
loop, the inner loop iterates
completely
• See
PalindromeTester.java
//********************************************************************
// PalindromeTester.java Author: Lewis/Loftus
//
// Demonstrates the use of nested while loops.
//********************************************************************
import java.util.Scanner;
public class PalindromeTester
{
//-----------------------------------------------------------------
// Tests strings to see if they are palindromes.
//-----------------------------------------------------------------
public static void main(String[] args)
{
String str, another = "y";
int left, right;
Scanner scan = new Scanner(System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println("Enter a potential palindrome:");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
continue
continue
while (str.charAt(left) == str.charAt(right) && left < right)
{
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println("That string is NOT a palindrome.");
else
System.out.println("That string IS a palindrome.");
System.out.println();
System.out.print("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}
continue
while (str.charAt(left) == str.charAt(right) && left < right)
{
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println("That string is NOT a palindrome.");
else
System.out.println("That string IS a palindrome.");
System.out.println();
System.out.print("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}
Sample Run
Enter a potential palindrome:
radar
That string IS a palindrome.
Test another palindrome (y/n)? y
Enter a potential palindrome:
able was I ere I saw elba
That string IS a palindrome.
Test another palindrome (y/n)? y
Enter a potential palindrome:
abracadabra
That string is NOT a palindrome.
Test another palindrome (y/n)? n

More Related Content

What's hot

Java se 8 language enhancements & features
Java se 8   language enhancements & featuresJava se 8   language enhancements & features
Java se 8 language enhancements & featuresJuarez Junior
 
Reflection in Pharo5
Reflection in Pharo5Reflection in Pharo5
Reflection in Pharo5Marcus Denker
 
How we migrated Zalando app to Swift3?
How we migrated Zalando app to Swift3?How we migrated Zalando app to Swift3?
How we migrated Zalando app to Swift3?Vijaya Prakash Kandel
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++Nitin Jawla
 
Managing state in modern React web applications
Managing state in modern React web applicationsManaging state in modern React web applications
Managing state in modern React web applicationsJon Preece
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5Marcus Denker
 
java in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyajava in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyaviratandodariya
 
Repository design pattern in laravel
Repository design pattern in laravelRepository design pattern in laravel
Repository design pattern in laravelSameer Poudel
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in PharoMarcus Denker
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10Minal Maniar
 
The Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyThe Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyDror Bereznitsky
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner Huda Alameen
 
Byteman - Carving up your Java code
Byteman - Carving up your Java codeByteman - Carving up your Java code
Byteman - Carving up your Java codeChris Sinjakli
 
Intro To Scala
Intro To ScalaIntro To Scala
Intro To Scalachambeda
 
Awesome Concurrency with Elixir Tasks
Awesome Concurrency with Elixir TasksAwesome Concurrency with Elixir Tasks
Awesome Concurrency with Elixir TasksJonathan Magen
 
PharoDAYS 2015: Pharo Status - by Markus Denker
PharoDAYS 2015: Pharo Status - by Markus DenkerPharoDAYS 2015: Pharo Status - by Markus Denker
PharoDAYS 2015: Pharo Status - by Markus DenkerPharo
 
Java Repetiotion Statements
Java Repetiotion StatementsJava Repetiotion Statements
Java Repetiotion StatementsHuda Alameen
 

What's hot (19)

Java se 8 language enhancements & features
Java se 8   language enhancements & featuresJava se 8   language enhancements & features
Java se 8 language enhancements & features
 
Reflection in Pharo5
Reflection in Pharo5Reflection in Pharo5
Reflection in Pharo5
 
Ifi7107 lesson4
Ifi7107 lesson4Ifi7107 lesson4
Ifi7107 lesson4
 
How we migrated Zalando app to Swift3?
How we migrated Zalando app to Swift3?How we migrated Zalando app to Swift3?
How we migrated Zalando app to Swift3?
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
 
Managing state in modern React web applications
Managing state in modern React web applicationsManaging state in modern React web applications
Managing state in modern React web applications
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
 
Loops
LoopsLoops
Loops
 
java in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyajava in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariya
 
Repository design pattern in laravel
Repository design pattern in laravelRepository design pattern in laravel
Repository design pattern in laravel
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
 
The Actor Model - Towards Better Concurrency
The Actor Model - Towards Better ConcurrencyThe Actor Model - Towards Better Concurrency
The Actor Model - Towards Better Concurrency
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
 
Byteman - Carving up your Java code
Byteman - Carving up your Java codeByteman - Carving up your Java code
Byteman - Carving up your Java code
 
Intro To Scala
Intro To ScalaIntro To Scala
Intro To Scala
 
Awesome Concurrency with Elixir Tasks
Awesome Concurrency with Elixir TasksAwesome Concurrency with Elixir Tasks
Awesome Concurrency with Elixir Tasks
 
PharoDAYS 2015: Pharo Status - by Markus Denker
PharoDAYS 2015: Pharo Status - by Markus DenkerPharoDAYS 2015: Pharo Status - by Markus Denker
PharoDAYS 2015: Pharo Status - by Markus Denker
 
Java Repetiotion Statements
Java Repetiotion StatementsJava Repetiotion Statements
Java Repetiotion Statements
 

Similar to Java Chapter 05 - Conditions & Loops: part 5

C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)SURBHI SAROHA
 
prt123.pptx
prt123.pptxprt123.pptx
prt123.pptxASADKS
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docxransayo
 
Week04
Week04Week04
Week04hccit
 
Java do-while Loop
Java do-while LoopJava do-while Loop
Java do-while LoopRhythm Suiwal
 
dizital pods session 5-loops.pptx
dizital pods session 5-loops.pptxdizital pods session 5-loops.pptx
dizital pods session 5-loops.pptxVijayKumarLokanadam
 
Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2sotlsoc
 
Microsoft word java
Microsoft word   javaMicrosoft word   java
Microsoft word javaRavi Purohit
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)jewelyngrace
 
Variables Arguments and control flow_UiPath.ppt
Variables Arguments and control flow_UiPath.pptVariables Arguments and control flow_UiPath.ppt
Variables Arguments and control flow_UiPath.pptRohit Radhakrishnan
 
Java Print method
Java  Print methodJava  Print method
Java Print methodHuda Alameen
 
Control structures repetition
Control structures   repetitionControl structures   repetition
Control structures repetitionOnline
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statementsVladislav Hadzhiyski
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)Niket Chandrawanshi
 
LOOPSFor LoopFor loop executes group of Java statements as long.pdf
LOOPSFor LoopFor loop executes group of Java statements as long.pdfLOOPSFor LoopFor loop executes group of Java statements as long.pdf
LOOPSFor LoopFor loop executes group of Java statements as long.pdfamaresh6333
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceKaniska Mandal
 

Similar to Java Chapter 05 - Conditions & Loops: part 5 (20)

Lesson 5
Lesson 5Lesson 5
Lesson 5
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 
Nested Loops in C.pptx
Nested Loops in C.pptxNested Loops in C.pptx
Nested Loops in C.pptx
 
prt123.pptx
prt123.pptxprt123.pptx
prt123.pptx
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
 
Week04
Week04Week04
Week04
 
Java do-while Loop
Java do-while LoopJava do-while Loop
Java do-while Loop
 
dizital pods session 5-loops.pptx
dizital pods session 5-loops.pptxdizital pods session 5-loops.pptx
dizital pods session 5-loops.pptx
 
Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2
 
Microsoft word java
Microsoft word   javaMicrosoft word   java
Microsoft word java
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)
 
Variables Arguments and control flow_UiPath.ppt
Variables Arguments and control flow_UiPath.pptVariables Arguments and control flow_UiPath.ppt
Variables Arguments and control flow_UiPath.ppt
 
Java Print method
Java  Print methodJava  Print method
Java Print method
 
Control structures repetition
Control structures   repetitionControl structures   repetition
Control structures repetition
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
LOOPSFor LoopFor loop executes group of Java statements as long.pdf
LOOPSFor LoopFor loop executes group of Java statements as long.pdfLOOPSFor LoopFor loop executes group of Java statements as long.pdf
LOOPSFor LoopFor loop executes group of Java statements as long.pdf
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
 
Ansible testing
Ansible   testingAnsible   testing
Ansible testing
 

More from DanWooster1

Upstate CSCI 540 Agile Development
Upstate CSCI 540 Agile DevelopmentUpstate CSCI 540 Agile Development
Upstate CSCI 540 Agile DevelopmentDanWooster1
 
Upstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testingUpstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testingDanWooster1
 
Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9DanWooster1
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4DanWooster1
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4DanWooster1
 
Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3DanWooster1
 
Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2DanWooster1
 
Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1DanWooster1
 
Upstate CSCI 525 Data Mining Chapter 3
Upstate CSCI 525 Data Mining Chapter 3Upstate CSCI 525 Data Mining Chapter 3
Upstate CSCI 525 Data Mining Chapter 3DanWooster1
 
Upstate CSCI 525 Data Mining Chapter 2
Upstate CSCI 525 Data Mining Chapter 2Upstate CSCI 525 Data Mining Chapter 2
Upstate CSCI 525 Data Mining Chapter 2DanWooster1
 
Upstate CSCI 525 Data Mining Chapter 1
Upstate CSCI 525 Data Mining Chapter 1Upstate CSCI 525 Data Mining Chapter 1
Upstate CSCI 525 Data Mining Chapter 1DanWooster1
 
Upstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - ArraysUpstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - ArraysDanWooster1
 
Upstate CSCI 200 Java Chapter 7 - OOP
Upstate CSCI 200 Java Chapter 7 - OOPUpstate CSCI 200 Java Chapter 7 - OOP
Upstate CSCI 200 Java Chapter 7 - OOPDanWooster1
 
CSCI 200 Java Chapter 03 Using Classes
CSCI 200 Java Chapter 03 Using ClassesCSCI 200 Java Chapter 03 Using Classes
CSCI 200 Java Chapter 03 Using ClassesDanWooster1
 
CSCI 200 Java Chapter 02 Data & Expressions
CSCI 200 Java Chapter 02 Data & ExpressionsCSCI 200 Java Chapter 02 Data & Expressions
CSCI 200 Java Chapter 02 Data & ExpressionsDanWooster1
 
CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01DanWooster1
 
CSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook SlidesCSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook SlidesDanWooster1
 
Chapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loopsChapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loopsDanWooster1
 
Upstate CSCI 450 jQuery
Upstate CSCI 450 jQueryUpstate CSCI 450 jQuery
Upstate CSCI 450 jQueryDanWooster1
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13DanWooster1
 

More from DanWooster1 (20)

Upstate CSCI 540 Agile Development
Upstate CSCI 540 Agile DevelopmentUpstate CSCI 540 Agile Development
Upstate CSCI 540 Agile Development
 
Upstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testingUpstate CSCI 540 Unit testing
Upstate CSCI 540 Unit testing
 
Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9Upstate CSCI 450 WebDev Chapter 9
Upstate CSCI 450 WebDev Chapter 9
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4
 
Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4Upstate CSCI 450 WebDev Chapter 4
Upstate CSCI 450 WebDev Chapter 4
 
Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3Upstate CSCI 450 WebDev Chapter 3
Upstate CSCI 450 WebDev Chapter 3
 
Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2Upstate CSCI 450 WebDev Chapter 2
Upstate CSCI 450 WebDev Chapter 2
 
Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1Upstate CSCI 450 WebDev Chapter 1
Upstate CSCI 450 WebDev Chapter 1
 
Upstate CSCI 525 Data Mining Chapter 3
Upstate CSCI 525 Data Mining Chapter 3Upstate CSCI 525 Data Mining Chapter 3
Upstate CSCI 525 Data Mining Chapter 3
 
Upstate CSCI 525 Data Mining Chapter 2
Upstate CSCI 525 Data Mining Chapter 2Upstate CSCI 525 Data Mining Chapter 2
Upstate CSCI 525 Data Mining Chapter 2
 
Upstate CSCI 525 Data Mining Chapter 1
Upstate CSCI 525 Data Mining Chapter 1Upstate CSCI 525 Data Mining Chapter 1
Upstate CSCI 525 Data Mining Chapter 1
 
Upstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - ArraysUpstate CSCI 200 Java Chapter 8 - Arrays
Upstate CSCI 200 Java Chapter 8 - Arrays
 
Upstate CSCI 200 Java Chapter 7 - OOP
Upstate CSCI 200 Java Chapter 7 - OOPUpstate CSCI 200 Java Chapter 7 - OOP
Upstate CSCI 200 Java Chapter 7 - OOP
 
CSCI 200 Java Chapter 03 Using Classes
CSCI 200 Java Chapter 03 Using ClassesCSCI 200 Java Chapter 03 Using Classes
CSCI 200 Java Chapter 03 Using Classes
 
CSCI 200 Java Chapter 02 Data & Expressions
CSCI 200 Java Chapter 02 Data & ExpressionsCSCI 200 Java Chapter 02 Data & Expressions
CSCI 200 Java Chapter 02 Data & Expressions
 
CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01CSCI 200 Java Chapter 01
CSCI 200 Java Chapter 01
 
CSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook SlidesCSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook Slides
 
Chapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loopsChapter 6 - More conditionals and loops
Chapter 6 - More conditionals and loops
 
Upstate CSCI 450 jQuery
Upstate CSCI 450 jQueryUpstate CSCI 450 jQuery
Upstate CSCI 450 jQuery
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13
 

Recently uploaded

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 

Java Chapter 05 - Conditions & Loops: part 5

  • 1. Chapter 5 Conditionals and Loops: Part 5 • Java Software Solutions • Foundations of Program Design • 9th Edition John Lewis William Loftus
  • 2. Outline Boolean Expressions The if Statement Comparing Data The while Statement Iterators The ArrayList Class
  • 3. Key Concept A loop allows a program to execute a statement multiple times.
  • 4. Repetition Statements • Repetition statements allow us to execute a statement multiple times • Often they are referred to as loops • Like conditional statements, they are controlled by boolean expressions • Java has three kinds of repetition statements: while, do, and for loops • The do and for loops are discussed in Chapter 6
  • 5. The while Statement • A while statement has the following syntax: while ( condition ) statement; • If the condition is true, the statement is executed • Then the condition is evaluated again, and if it is still true, the statement is executed again • The statement is executed repeatedly until the condition becomes false
  • 6. Logic of a while Loop statement true false condition evaluated
  • 7. The while Statement • An example of a while statement: • If the condition of a while loop is false initially, the statement is never executed • Therefore, the body of a while loop will execute zero or more times • int count = 1; • while (count <= 5) • { • System.out.println(count); • count++; • }
  • 8. Sentinel Values • Let's look at some examples of loop processing • A loop can be used to maintain a running sum • A sentinel value is a special input value that represents the end of input • See Average.java
  • 9. //******************************************************************** // Average.java Author: Lewis/Loftus // // Demonstrates the use of a while loop, a sentinel value, and a // running sum. //******************************************************************** import java.text.DecimalFormat; import java.util.Scanner; public class Average { //----------------------------------------------------------------- // Computes the average of a set of values entered by the user. // The running sum is printed as the numbers are entered. //----------------------------------------------------------------- public static void main(String[] args) { int sum = 0, value, count = 0; double average; Scanner scan = new Scanner(System.in); System.out.print("Enter an integer (0 to quit): "); value = scan.nextInt(); continue
  • 10. continue while (value != 0) // sentinel value of 0 to terminate loop { count++; sum += value; System.out.println("The sum so far is " + sum); System.out.print("Enter an integer (0 to quit): "); value = scan.nextInt(); } continue
  • 11. continue System.out.println(); if (count == 0) System.out.println("No values were entered."); else { average = (double)sum / count; DecimalFormat fmt = new DecimalFormat("0.###"); System.out.println("The average is " + fmt.format(average)); } } }
  • 12. continue System.out.println(); if (count == 0) System.out.println("No values were entered."); else { average = (double)sum / count; DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println("The average is " + fmt.format(average)); } } } Sample Run Enter an integer (0 to quit): 25 The sum so far is 25 Enter an integer (0 to quit): 164 The sum so far is 189 Enter an integer (0 to quit): -14 The sum so far is 175 Enter an integer (0 to quit): 84 The sum so far is 259 Enter an integer (0 to quit): 12 The sum so far is 271 Enter an integer (0 to quit): -35 The sum so far is 236 Enter an integer (0 to quit): 0 The average is 39.333
  • 13. Input Validation • A loop can also be used for input validation, making a program more robust • It's generally a good idea to verify that input is valid (in whatever sense) when possible • See WinPercentage.java
  • 14. //******************************************************************** // WinPercentage.java Author: Lewis/Loftus // // Demonstrates the use of a while loop for input validation. //******************************************************************** import java.text.NumberFormat; import java.util.Scanner; public class WinPercentage { //----------------------------------------------------------------- // Computes the percentage of games won by a team. //----------------------------------------------------------------- public static void main(String[] args) { final int NUM_GAMES = 12; int won; double ratio; Scanner scan = new Scanner(System.in); System.out.print("Enter the number of games won (0 to " + NUM_GAMES + "): "); won = scan.nextInt(); continue
  • 15. continue while (won < 0 || won > NUM_GAMES) { System.out.print("Invalid input. Please reenter: "); won = scan.nextInt(); } ratio = (double)won / NUM_GAMES; NumberFormat fmt = NumberFormat.getPercentInstance(); System.out.println(); System.out.println("Winning percentage: " + fmt.format(ratio)); } }
  • 16. continue while (won < 0 || won > NUM_GAMES) { System.out.print("Invalid input. Please reenter: "); won = scan.nextInt(); } ratio = (double)won / NUM_GAMES; NumberFormat fmt = NumberFormat.getPercentInstance(); System.out.println(); System.out.println("Winning percentage: " + fmt.format(ratio)); } } Sample Run Enter the number of games won (0 to 12): -5 Invalid input. Please reenter: 13 Invalid input. Please reenter: 7 Winning percentage: 58%
  • 17. Infinite Loops • The body of a while loop eventually must make the condition false • If not, it is called an infinite loop, which will execute until the user interrupts the program • This is a common logical error • You should always double check the logic of a program to ensure that your loops will terminate normally
  • 18. Infinite Loops • An example of an infinite loop: • This loop will continue executing until interrupted (Control-C) or until an underflow error occurs int count = 1; while (count <= 25) { System.out.println(count); count = count - 1; }
  • 19. Nested Loops • Similar to nested if statements, loops can be nested as well • That is, the body of a loop can contain another loop • For each iteration of the outer loop, the inner loop iterates completely • See PalindromeTester.java
  • 20. //******************************************************************** // PalindromeTester.java Author: Lewis/Loftus // // Demonstrates the use of nested while loops. //******************************************************************** import java.util.Scanner; public class PalindromeTester { //----------------------------------------------------------------- // Tests strings to see if they are palindromes. //----------------------------------------------------------------- public static void main(String[] args) { String str, another = "y"; int left, right; Scanner scan = new Scanner(System.in); while (another.equalsIgnoreCase("y")) // allows y or Y { System.out.println("Enter a potential palindrome:"); str = scan.nextLine(); left = 0; right = str.length() - 1; continue
  • 21. continue while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } System.out.println(); if (left < right) System.out.println("That string is NOT a palindrome."); else System.out.println("That string IS a palindrome."); System.out.println(); System.out.print("Test another palindrome (y/n)? "); another = scan.nextLine(); } } }
  • 22. continue while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } System.out.println(); if (left < right) System.out.println("That string is NOT a palindrome."); else System.out.println("That string IS a palindrome."); System.out.println(); System.out.print("Test another palindrome (y/n)? "); another = scan.nextLine(); } } } Sample Run Enter a potential palindrome: radar That string IS a palindrome. Test another palindrome (y/n)? y Enter a potential palindrome: able was I ere I saw elba That string IS a palindrome. Test another palindrome (y/n)? y Enter a potential palindrome: abracadabra That string is NOT a palindrome. Test another palindrome (y/n)? n