Lecture 4 - Loops and Files
Lecture 4 - Loops and Files
Introduction to
Computer Science
int test = 0;
while( check test is less than 5 here)
{
// Your scanner code goes here
}
The while loop Flowchart
true
boolean
statement(s)
expression?
false
Infinite Loops
while (condition)
{
statement;
statement;
statement;
}
Activity 8 (will be included in quiz grade)
• Write a while loop to find the sum of first 500 numbers. Display
the result at the end of the loop run.
1+2+3……..+499 + 500
• Modify the above code to break from loop when the number is
199.
• Modify the code to enter a positive number n and find the sum up
to that number.
The while Loop for Input Validation
statement(s)
true
boolean
expression?
false
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);
}
The for Loop Flowchart
boolean true
statement(s) update
expression?
false
The Sections of The for Loop
• 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
Writing Text To a File
Pass the name of the file that you Warning: if the file
wish to open as an argument to the already exists, it will be
PrintWriter constructor. erased and replaced with
a new file.
The PrintWriter Class
• The PrintWriter class allows you to write data to a file
using the print and println methods, as you have been
using to display data on the screen.
• Just as with the System.out object, the println method
of the PrintWriter class will place a newline character
after the written data.
• The print method writes data without writing the
newline character.
The PrintWriter Class
Open the file.
FileWriter fw =
new FileWriter("names.dat", true);
PrintWriter outFile =
new PrintWriter("A:\\PriceList.txt");
Specifying a File Location