CSO Gaddis Java Chapter04 7e
CSO Gaddis Java Chapter04 7e
CSO Gaddis Java Chapter04 7e
7th Edition
Chapter 4
Loops and Files
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Chapter Topics (1 of 2)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Chapter Topics (2 of 2)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The Increment and Decrement Operators
• There are numerous times where a variable must
simply be incremented or decremented.
number = number + 1;
number = number – 1;
• Example: IncrementDecrement.java
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Differences Between Prefix and Postfix
• When an increment or decrement are the only
operations in a statement, there is no difference
between prefix and postfix notation.
• When used in an expression:
– prefix notation indicates that the variable will be
incremented or decremented prior to the rest of the
equation being evaluated.
– postfix notation indicates that the variable will be
incremented or decremented after the rest of the
equation has been evaluated.
• Example: Prefix.java
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The while Loop (1 of 2)
• Java provides three different looping structures.
• The while loop has the form:
while(condition)
{
statements;
}
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The while Loop (2 of 2)
• Care must be taken to set the condition to false
somewhere in the loop so the loop will end.
• Loops that do not end are called infinite loops.
• A while loop executes 0 or more times. If the
condition is false, the loop will not execute.
• Example: WhileLoop.java
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The while loop Flowchart
true
boolean
statement(s)
expression?
false
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Infinite Loops (1 of 2)
int x = 20;
while(x > 0)
{
System.out.println("x is greater
than 0");
x--;
}
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Block Statements in Loops
while (condition)
{
statement;
statement;
statement;
}
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The while Loop for Input Validation
• Input validation is the process of ensuring that user input is valid.
System.out.print("Enter a number in the " +
"range of 1 through 100: ");
number = keyboard.nextInt();
// Validate the input.
while (number < 1 || number > 100)
{
System.out.println("That number is invalid.");
System.out.print("Enter a number in the " +
"range of 1 through 100: ");
number = keyboard.nextInt();
}
• Example: SoccerTeams.java
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The do-while Loop
• The do-while loop is a post-test loop, which means it
will execute the loop prior to testing the condition.
• The do-while loop (sometimes called called a do loop)
takes the form:
do
{
statement(s);
}while (condition);
• Example: TestAverage1.java
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The do-while Loop Flowchart
statement(s)
true
boolean
expression?
false
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The for Loop
• The for loop is a pre-test loop.
• The for loop allows the programmer to initialize a
control variable, test a condition, and modify the control
variable all in one line of code.
• The for loop takes the form:
for(initialization; test; update)
{
statement(s);
}
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The for Loop Flowchart
boolean true
statement(s) update
expression?
false
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The Sections of The for Loop
• The initialization section of the for loop allows
the loop to initialize its own control variable.
• The test section of the for statement acts in
the same manner as the condition section of a
while loop.
• The update section of the for loop is the last
thing to execute at the end of each loop.
• Example: UserSquares.java
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The for Loop Initialization
• The initialization section of a for loop is
optional; however, it is usually provided.
• Typically, for loops initialize a counter variable
that will be tested by the test section of the loop
and updated by the update section.
• The initialization section can initialize multiple
variables.
• Variables declared in this section have scope
only for the for loop.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The Update Expression
• The update expression is usually used to
increment or decrement the counter variable(s)
declared in the initialization section of the for
loop.
• The update section of the loop executes last in
the loop.
• The update section may update multiple
variables.
• Each variable updated is executed as if it were
on a line by itself.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Modifying The Control Variable
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Multiple Initializations and Updates
• The for loop may initialize and update multiple variables.
for(int i = 5, int j = 0; i < 10 || j < 20; i++,
j+=2)
{
statement(s);
}
• Note that the only parts of a for loop that are mandatory are the
semicolons.
for(;;)
{
statement(s);
} // infinite loop
• If left out, the test section defaults to true.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Running Totals
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Logic for Calculating a Running Total
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Sentinel Values
• Sometimes the end point of input data is not known.
• A sentinel value can be used to notify the program to
stop acquiring input.
• If it is a user input, the user could be prompted to input
data that is not normally in the input data range (i.e. –1
where normal input would be positive.)
• Programs that get file input typically use the end-of-file
marker to stop acquiring input data.
• Example: SoccerPoints.java
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Nested Loops
• Like if statements, loops can be nested.
• If a loop is nested, the inner loop will execute all of its
iterations for each time the outer loop executes once.
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
loop statements;
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The break Statement
• The break statement can be used to
abnormally terminate a loop.
• The use of the break statement in loops
bypasses the normal mechanisms and makes
the code hard to read and maintain.
• It is considered bad form to use the break
statement in this manner.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The continue Statement
• The continue statement will cause the
currently executing iteration of a loop to
terminate and the next iteration will begin.
• The continue statement will cause the
evaluation of the condition in while and for
loops.
• Like the break statement, the continue
statement should be avoided because it makes
the code hard to read and debug.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Deciding Which Loops to Use
• The while loop:
– Pretest loop
– Use it where you do not want the statements to execute if the
condition is false in the beginning.
• The do-while loop:
– Post-test loop
– Use it where you want the statements to execute at least one
time.
• The for loop:
– Pretest loop
– Use it where there is some type of counting variable that can be
evaluated.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
File Input and Output
• Reentering data all the time could get tedious for the
user.
• The data can be saved to a file.
– Files can be input files or output files.
• Files:
– Files have to be opened.
– Data is then written to the file.
– The file must be closed prior to program termination.
• In general, there are two types of files:
– binary
– text
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Writing Text To a File
Pass the name of the file that you Warning: if the file
wish to open as an argument to already exists, it will be
the PrintWriter constructor. erased and replaced
with a new file.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The PrintWriter Class (1 of 3)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The PrintWriter Class (2 of 3)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
The PrintWriter Class (3 of 3)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Exceptions (1 of 2)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Exceptions (2 of 2)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Appending Text to a File
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Specifying a File Location (1 of 2)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Specifying a File Location (2 of 2)
• This is only necessary if the backslash is in a
string literal.
• If the backslash is in a String object then it will
be handled properly.
• Fortunately, Java allows Unix style filenames
using the forward slash (/) to separate
directories:
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Reading Data From a File (1 of 3)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Reading Data From a File (2 of 3)
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Reading Data From a File (3 of 3)
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Exceptions
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Detecting The End of a File
• The Scanner class’s hasNext() method will
return true if another item can be read from the
file.
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Read until the end of the file.
while (inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println(str);
}
inputFile.close();// close the file
when done.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Detecting the End of a File
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Generating Random Numbers with the
Random Class
• Some applications, such as games and
simulations, require the use of randomly
generated numbers.
• The Java API has a class, Random, for this
purpose. To use the Random class, use the
following import statement and create an
instance of the class.
import java.util.Random;
Random randomNumbers = new Random();
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved
Some Methods of the
Random Class
Method Description
This work is protected by United States copyright laws and is provided solely
for the use of instructions in teaching their courses and assessing student
learning. dissemination or sale of any part of this work (including on the
World Wide Web) will destroy the integrity of the work and is not permit-
ted. The work and materials from it should never be made available to
students except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and the needs of
other instructors who rely on these materials.
Copyright © 2019, 2016, 2013 Pearson Education, Inc. All Rights Reserved