CHAPTER 4 Loops and Files
CHAPTER 4
Loops and Files
4-2
Chapter Topics
Chapter 4 discusses the following main topics:
– The Increment and Decrement Operators
– The while Loop
– Using the while Loop for Input Validation
– The do-while Loop
– The for Loop
– Running Totals and Sentinel Values
4-3
Chapter Topics
Chapter 4 discusses the following main topics:
– Nested Loops
– The break and continue Statements
– Deciding Which Loop to Use
– Introduction to File Input and Output
– Generating Random Numbers with the Random
class
4-4
The Increment and Decrement Operators
• There are numerous times where a variable must simply
be incremented or decremented.
number = number + 1;
number = number – 1;
• Java provide shortened ways to increment and decrement
a variable’s value.
• Using the ++ or -- unary operators, this task can be
completed quickly.
number++; or ++number;
number--; or --number;
• Example: IncrementDecrement.java
4-5
The Increment and Decrement Operatorsint number = 0;
String strInitNum = "Initial value of number is %d.\n";
System.out.printf(strInitNum, number);
String strNum2Plus = "number++ is %d.\n";
String strNum2Minus = "number-- is %d.\n";
String str2PlusNum = "++number is %d.\n";
String str2MinusNum = "--number is %d.\n";
number++;
System.out.printf(strNum2Plus, number);
number--;
System.out.printf(strNum2Minus, number);
System.out.printf(strNum2Plus, number++);
System.out.printf(strNum2Minus, number--);
System.out.printf("The final value of number is %d.\n", number);
4-6
The Increment and Decrement Operatorsint number = 0;
String strInitNum = "Initial value of number is %d.\n";
System.out.printf(strInitNum, number);
String strNum2Plus = "number++ is %d.\n";
String strNum2Minus = "number-- is %d.\n";
String str2PlusNum = "++number is %d.\n";
String str2MinusNum = "--number is %d.\n";
number++;
System.out.printf(strNum2Plus, number);
number--;
System.out.printf(strNum2Minus, number);
System.out.printf(strNum2Plus, number++);
System.out.printf(strNum2Minus, number--);
System.out.printf("The number storage has %d.\n", number);
Initial value of number is
0.
number++ is 1.
number-- is 0.
number++ is 0.
number-- is 1.
The number storage has 0.
4-7
The Increment and Decrement Operators
number = 0;
System.out.printf(strInitNum, number);
++number;
System.out.printf(str2PlusNum , number);
--number;
System.out.printf(str2MinusNum, number);
System.out.printf(str2PlusNum , ++number);
System.out.printf(str2MinusNum, --number);
System.out.printf("The number storage has %d.\n", number);
Initial value of number is 0.
++number is 1.
--number is 0.
++number is 1.
--number is 0.
The number storage has 0.
4-8
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.
e.g., num++; ++num; nos--; -- nos;
• 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.
e.g., sum = sum + ++num; sum = ++num + sum;
postfix notation indicates that the variable will be incremented or decremented after the rest of the equation has been evaluated.
e.g., sum = sum + num++; sum = num++ + sum;
• Example: Prefix.java
int sum = 10; int num = 1;sum = sum + ++num;System.out.println("sum is " + sum + ". num is " + num);
sum = 10; num = 1;sum = ++num + sum;System.out.println("sum is " + sum + ". num is " + num);
sum = 10; num = 1;sum = sum + num++;System.out.println("sum is " + sum + ". num is " + num);
sum = 10; num = 1;sum = num++ + sum;System.out.println("sum is " + sum + ". num is " + num);
sum is 12. num is 2sum is 12. num is 2sum is 11. num is 2sum is 11. num is 2
int sum = 10; int num = 1;sum = sum + --num;System.out.println("sum is " + sum + ". num is " + num);sum = 10; num = 1;sum = --num + sum;System.out.println("sum is " + sum + ". num is " + num);
sum = 10; num = 1;sum = sum + num--;System.out.println("sum is " + sum + ". num is " + num);
sum = 10; num = 1;sum = num-- + sum;System.out.println("sum is " + sum + ". num is " + num);
sum is 10. num is 0sum is 10. num is 0sum is 11. num is 0sum is 11. num is 0
4-11
Differences Between Prefix and Postfix
int sum = number = 0;
sum = sum + ++number; //number=number+1; sum=sum+number;
System.out.printf("Sum is %d.\n", sum);
sum = number = 0;
sum = ++number + sum; //number=number+1; sum=sum+number;
System.out.printf("Sum is %d.\n", sum);
sum = number = 0;
sum = sum + number++; //sum=sum+number; number=number+1;
System.out.printf("Sum is %d.\n", sum);
System.out.printf("The value of number is %d.\n", number);
sum = number = 0;
sum = number++ + sum; //sum = number + sum; number=number+1;
System.out.printf("Sum is %d.\n", sum);
System.out.printf("The value of number is %d.\n", number);
Sum is 1.
Sum is 1.
Sum is 0.
The value of number is 1.
Sum is 0.
The value of number is 1.
4-12
The while Loop
• Java provides three different looping structures.
• The while loop has the form:
while(condition)
{
statements;
}
• While the condition is true, the statements will execute repeatedly.
• The while loop is a pretest loop, which means that it will test the value of the condition prior to executing the loop.
C
S
t
fint x = 0, y = 3;
while( x <= y)
{
x = x + 1;
y = y – 1;
}
System.out.printf(“x is %d and y is %d.\n”, x, y);
Result is: x is 2 and y is 1.
int x = 0, y = 3;while( x <= y){
x = x + 2;y = y - 1;System.out.printf("x is %d and y is %d.\n", x, y);
}System.out.printf("x is %d and y is %d.\n", x, y);
x is 2 and y is 2.x is 4 and y is 1.x is 4 and y is 1.
4-14
The while Loop
• 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
int x = 0, y = 3;
while( x > y)
{
x = x + 1;
y = y – 1;
System.out.println(“I was here!”);
}
System.out.printf(“x is %d and y is %d.\n”, x, y);
Result is: x is 0 and y is 3.
4-15
The while loop Flowchart
statement(s)
true
boolean
expression?false
while (Boolean expression)
{
statements;
}
4-16
Infinite Loops
• In order for a while loop to end, the condition must become false. The following loop will not end:
int x = 20;while(x > 0){
System.out.println("x is greater " + "than 0");
String str = “x = %d is greater than 0.\n”;System.out.printf(str, x)
}
• The variable x never gets decremented so it will always be greater than 0.
• Adding the x-- above fixes the problem.
4-17
Infinite Loops
• This version of the loop decrements x during each
iteration:
int x = 20;while(x > 0){
System.out.println("x is greater " + "than 0");
String str = “x = %d is greater than 0.\n”;System.out.printf(str, x);x--;
}
4-18
Block Statements in Loops
• Curly braces are required to enclose block statement while loops. (like block if statements)
while (condition)
{
statement;
statement;
…
statement;
}
4-19
Block Statements in Loops
• Curly braces are required to enclose block statement while loops. (like block if statements)
int c = 3;
while (c > 0)
c = c - 1;
System.out.printf("c is %d.\n", c);
c = 3;
while (c > 0) {
c = c - 1;
System.out.printf("c is %d.\n", c);
}
c is 0.
c is 2.
c is 1.
c is 0.
4-20
The while Loop for Input Validation
• Input validation is the process of ensuring that user input is valid.
Scanner keyboard = new Scanner(System.in);
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();
}
System.out.println(“A number is “ + number + ".");
• Example: SoccerTeams.java
4-21
The while Loop for Input Validation
• Input validation is the process of ensuring that user input is valid.
Scanner keyboard = new Scanner(System.in);
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();
}
System.out.println(“A number is “ + number + ".");
• Example: SoccerTeams.java
Enter a number in the range of 1 through 100: 101
That number is invalid.
Enter a number in the range of 1 through 100:
That number is invalid.
Enter a number in the range of 1 through 100: 51
A number is 51.
4-22
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 also called a do loop)
takes the form:
do
{
statement(s);
} while (condition);
• Example: TestAverage1.java
4-23
The do-while Loop Flowchart
statement(s)
trueboolean
expression?
false
do
{
statement(s);
} while (boolean expression);
4-24
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);
}
• See example: Squares.java
4-25
The for Loop Flowchart
statement(s)
true
boolean
expression?
false
update
initialization
for(initialization; test; update)
{
statement(s);
}
4-26
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 whileloop.
• The update section of the for loop is the last thing to execute at the end of each loop.
• Example: UserSquares.java
for (int i = 0; i < 5; i++) {
System.out.println(i);}//System.out.println(i); //i is undefined here!
int j = 0;do{
System.out.println(j);j++;
}while (j < 5);
int k = 0;
while (k < 5)
{
System.out.println(k);
k++;
}
012340123401234
What are the differences among for statement, do-while statement and while statement?
See the next two slides.
package chapter04;import java.util.Scanner;
public class Chapter04 {
public static void main(String[] args) {Scanner kbInput = new Scanner(System.in);System.out.println("Enter an integer as an index: ");int indexReserved = kbInput.nextInt();int index = indexReserved;
for ( ; index >= 5; index--) {System.out.println("for loop has an output: " + index);
} //end of for
index = indexReserved;do {
System.out.println("do while has an output: " + index);index--;
} while (index >= 5);
index = indexReserved;while (index >= 5 ) {
System.out.println("while has an output: " + index);index--;
} //end of while} //end of main
}
Enter an integer as an index: 5for loop has an output: 5do while has an output: 5while has an output: 5
Enter an integer as an index: 0do while has an output: 0
Scope of the variable iindex;
for (int iindex=6 ; iindex >= 5; iindex--){
System.out.println("for loop has an output: " + iindex);}System.out.println("for loop has an output: " + iindex);
Exception in thread "main" java.lang.Error: Unresolved compilation problem: iindex cannot be resolved to a variable
int iindex;for (iindex=6 ; iindex >= 5; iindex--){
System.out.println("for loop has an output: " + iindex);}System.out.println("for loop has an output: " + iindex);
Scope of the variable iindex;
int iindex;for (iindex=6 ; iindex >= 5; iindex--){
System.out.println("for loop has an output: " + iindex);
}System.out.println("for loop has an output: " + iindex);
for loop has an output: 6for loop has an output: 5for loop has an output: 4
4-31
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 whileloop.
• The update section of the for loop is the last thing to execute at the end of each loop.
• Example: UserSquares.java
4-32
The for Loop Initialization
• The initialization section of a for loop is optional; however, it is usually provided.
• Typically, for loops initialize a counter variablethat 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. for (int i = 0; i < 5; i++)
{
System.out.println(i);
}
System.out.println(i); //i is undefined here!
4-33
The for Loop Initialization
• The initialization section of a for loop is optional; however, it is usually provided.
• Typically, for loops initialize a counter variablethat 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.
for (int i = 0; i < 5; i++) {
System.out.println(i);}//System.out.println(i); //i is undefined here!
int c = 0;for (; c < 5; c++) {
System.out.println(c);}System.out.println(c); //i is undefined here!
01234012345
4-34
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.
4-35
Modifying The Control Variable
• You should avoid updating the control variable of a
for loop within the body of the loop.
• The update section should be used to update the
control variable.
• Updating the control variable in the for loop body
leads to hard to maintain code and difficult
debugging.
4-36
Multiple Initializations and Updates
for (int x = 0, y = -1; (x < 3 || y < 3); x++, y++)
{
System.out.printf("x = %d and y = %d.\n", x, y);
}
//System.out.printf("x = %d and y = %d.\n", x, y);
//x and y cannot be resolved to variable
int x, y;
for (x = 0, y = -1; (x < 3 || y < 3); x++, y++)
{
System.out.printf("x = %d and y = %d.\n", x, y);
}
System.out.printf("Outside for loop: x = %d and y = %d.\n", x, y);
4-37
Multiple Initializations and Updates
for (int x = 0, y = -1; (x < 3 || y < 3); x++, y++)
{
System.out.printf("x = %d and y = %d.\n", x, y);
}
//System.out.printf("x = %d and y = %d.\n", x, y);
//x and y cannot be resolved to a variable
int x, y;
for (x = 0, y = -1; (x < 3 || y < 3); x++, y++)
{
System.out.printf("x = %d and y = %d.\n", x, y);
}
System.out.printf("Outside for loop: x = %d and y = %d.\n", x, y);
x = 0 and y = -1.
x = 1 and y = 0.
x = 2 and y = 1.
x = 3 and y = 2.
x = 0 and y = -1.
x = 1 and y = 0.
x = 2 and y = 1.
x = 3 and y = 2.
Outside for
loop: x = 4 and
y = 3.
4-38
Running Totals
• Loops allow the program to keep running totals while
evaluating data.
• Imagine needing to keep a running total of user input.
• Example: TotalSales.java
Logic for Calculating a Running Total
4-39
Set accumulator to 0
Is there another
number to read?
Add the number to
the accumulator
Read the next
number
No
(false)
Yes
(true)
Logic for Calculating a Running Total
4-40
4-41
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 an 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
import javax.swing.JOptionPane;
public class TotalSales {public static void main(String[] args) {
double sumNumbers = 0;final int totalNumbers;double number;String input = JOptionPane.showInputDialog("Enter " + "total numbers to be entered: ");totalNumbers = Integer.parseInt(input);
for(int count=0; count < totalNumbers; count++ ){
input = JOptionPane.showInputDialog("Enter " +"a number: ");
//number = Double.parseDouble(input);sumNumbers = sumNumbers + Double.parseDouble(input);
}JOptionPane.showMessageDialog(null,
String.format("The sum of %d numbers is %.2f.", totalNumbers, sumNumbers));
System.exit(0);}
}
import java.util.Scanner;public class TotalSales {
public static void main(String[] args) {int sumNumbers = 0;int totalNumbers = 0;int number;
Scanner kb = new Scanner(System.in);
System.out.println("Enter a positive number, " +
"otherwise -1 for ending");
number = kb.nextInt();
while(number != -1)
{
totalNumbers++;
sumNumbers += number;
System.out.println("Enter a positive number, " +
"otherwise -1 for ending");
number = kb.nextInt();
}
System.out.printf("Sum of the %d numbers is %d.\n",
totalNumbers, sumNumbers );
Enter a positive number, otherwise -1 for ending-1Sum of the 0 numbers is 0.00.
Enter a positive number, otherwise -1 for ending101.01Enter a positive number, otherwise -1 for ending-1Sum of the 1 numbers is 101.01.
Enter a positive number, otherwise -1 for ending202.02Enter a positive number, otherwise -1 for ending303.0399Enter a positive number, otherwise -1 for ending-1Sum of the 2 numbers is 505.06.
4-45
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;
• The loop statements in this example will execute 100
times.
• Example: Clock.java
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++)loop statements;
}
final int iLimit = 3;final int jLimit = 5;
for(int i = 0; i < iLimit; i++){
System.out.println("i is " + i);
for(int j = 0; j < jLimit; j++)System.out.println(" j is " + j);
}
i is 0j is 0j is 1j is 2j is 3j is 4
i is 1j is 0j is 1j is 2j is 3j is 4
i is 2j is 0j is 1j is 2j is 3j is 4
final int iLimit = 3;final int jLimit = 5;
for(int i = 0; i < iLimit; i++){System.out.println("");
for(int j = 0; j < jLimit; j++)System.out.print(j + " ");}System.out.println("\nThis is");
int x = 0, col = 0;for(int row = 0; row < iLimit; row++){System.out.println("");
for(; col < (row+1)*jLimit; col++){System.out.print(col + " ");x = col + 1;}x = col + 1;}}}
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 This is
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
4-48
Nested Loops
• 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;
for(int i = 0; i < 10; i++)
{for(int j = 0; j < 10; j++){
loop statements;}//end inner for_loop
}//end outer for_loop
4-49
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.
char switchExpr;switchExpr = 'a';switch (switchExpr){
case 'A’:case 'a’:
System.out.println("This is one!");break;
case 'B’:case 'b’:
System.out.println("This is two!");break;
default:System.out.println("This is out!");
}
import javax.swing.JOptionPane;
public class ReadWriteFile {public static void main(String[] args) {
char switchExpr;//switchExpr = 'a';String str = JOptionPane.showInputDialog("Enter a character: ");switchExpr = str.charAt(0);
switch (switchExpr){case 'A': case 'a':
System.out.println("This is one!");break;
case 'B':case 'b':
System.out.println("This is two!");break;
default:System.out.println("This is out!");
}System.exit(0);
}}
String str = JOptionPane.showInputDialog("Enter " + "a word:");
str = str.toUpperCase();switch (str){
case "PETER":System.out.printf("The name is %s.\n", str);break;
case "PAUL":System.out.printf("The name is %s.\n", str);break;
default:System.out.println("No Peter and Paul.");
}
import javax.swing.JOptionPane;
public class ReadWriteFile {public static void main(String[] args) {
String str = JOptionPane.showInputDialog("Enter " + "a word:");//str = str.toUpperCase();if (str.equalsIgnoreCase("PETER"))
System.out.printf("The name is %s.\n", str);
else if(str.equalsIgnoreCase("PAUL"))System.out.printf("The name is %s.\n", str);
elseSystem.out.println("No Peter and Paul.");
System.exit(0);
}}
if (str.equals("PETER"))switchExpr = str.charAt(0);
else if ("Paul".equalsIgnoreCase(str))switchExpr = str.charAt(1);
else switchExpr = str.charAt(0);
switch (switchExpr){
case 'P':case 'p':
System.out.println("This is one, P!");break;
case 'a’:case 'A’:
System.out.println("This is two, Paul!");break;
default:System.out.println("This is out Not p from" +
" Peter or not a from Paul!");}
import javax.swing.JOptionPane;
public class ReadWriteFile {public static void main(String[] args) {
String str = JOptionPane.showInputDialog("Enter "
+ "a word:");
System.out.println("The str " + str + “ compareTo(\"PETER\") is "+ str.compareTo("PETER") );
System.exit(0);}
}
The str PETER compareTo("PETER") is 0
The str PETERABC compareTo("PETER") is 3The str PETEr compareTo("PETER") is 32
//ASCII code for r is 114 and R is 82 and the difference is 114-82 = 32
4-56
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.
Import javax.swing.JOptionPane;public class TotalSales {
public static void main(String[] args) {double sumNumbers = 0;
//int totalNumbers = 5;
double number;
String task = "Enter total numbers to be entered: ";
String title = "Determine Sum of Numbers";
String input = JOptionPane.showInputDialog(null, task, title, JOptionPane.QUESTION_MESSAGE);
//create a name constant with the modifier final.
final int totalNumbers = Integer.parseInt(input);
for(int count=0; count < totalNumbers; count++ )
{
input = JOptionPane.showInputDialog(null, "Enter a number: ", title, JOptionPane.QUESTION_MESSAGE);
//number = Double.parseDouble(input);
sumNumbers = sumNumbers + Double.parseDouble(input);
int yesNoCancel = JOptionPane.showConfirmDialog(null, "Continue to enter a number?", title + "Selection One!",
JOptionPane.YES_NO_CANCEL_OPTION);
if (yesNoCancel == JOptionPane.NO_OPTION)
break;
else if (yesNoCancel == JOptionPane.CANCEL_OPTION)
{
int yesNoContinue = JOptionPane.showConfirmDialog(null, "Do you continue to enter a number?",
title + "Selection One!", JOptionPane.YES_NO_OPTION);
if (yesNoContinue == JOptionPane.YES_OPTION)
continue;
else
break;
}
} //end for
JOptionPane.showMessageDialog(null, String.format("The sum of %d numbers is %.2f.", totalNumbers, sumNumbers),
title, JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}}
Import javax.swing.JOptionPane;public class TotalSales {
public static void main(String[] args) {double sumNumbers = 0, number;
int totalCount = 0;
String task = "Enter total numbers to be entered: ";
String title = "Determine Sum of Numbers";
String input = JOptionPane.showInputDialog(null, task, title, JOptionPane.QUESTION_MESSAGE);
//create a name constant with the modifier final.
final int totalNumbers = Integer.parseInt(input);
for(int count=0; count < totalNumbers; count++ )
{
input = JOptionPane.showInputDialog(null, "Enter a number: ", title, JOptionPane.QUESTION_MESSAGE);
sumNumbers = sumNumbers + Double.parseDouble(input);
totalCount = totalCount + 1;
int yesNoCancel = JOptionPane.showConfirmDialog(null, "Continue to enter a number?", title + "Selection One!",
JOptionPane.YES_NO_CANCEL_OPTION);
if (yesNoCancel == JOptionPane.NO_OPTION)
break;
else if (yesNoCancel == JOptionPane.CANCEL_OPTION)
{
int yesNoContinue = JOptionPane.showConfirmDialog(null, "Do you continue to enter a number?",
title + "Selection One!", JOptionPane.YES_NO_OPTION);
if (yesNoContinue == JOptionPane.YES_OPTION)
continue;
else
break;
}
} //end for
if (totalNumbers <= totalCount)
JOptionPane.showMessageDialog(null, String.format("The sum of %d numbers is %.2f.", totalNumbers, sumNumbers),
title, JOptionPane.INFORMATION_MESSAGE);
else JOptionPane.showMessageDialog(null, String.format("The sum of %d numbers is %.2f.", totalCount, sumNumbers),
title, JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}}
4-59
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.
4-60
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 ….. Plain Text (*.txt)
4-61
Writing Text To a File
• To open a file for text output you create an instance of the
PrintWriter class.
PrintWriter outputFile = new PrintWriter("StudentData.txt");
Pass the name of the file that
you wish to open as an
argument to the
PrintWriter constructor.
Warning: if the file
already exists, it will
be erased and
replaced with a new
file.
4-62
The PrintWriter Class
• The PrintWriter class allows you to write data to a file using the print and printlnmethods, 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.
Use \r (return) instead of \n
for writing data on files.
4-63
The PrintWriter Class
PrintWriter outputFile = new PrintWriter("Names.txt");
outputFile.println("Chris");outputFile.println("Kathryn");outputFile.println("Jean");outputFile.close();
Open the file.
Write data to the file.
Close the file.
4-64
The PrintWriter Class
• To use the PrintWriter class, put the following
import statement at the top of the source file:
import java.io.*;
• See example: FileWriteDemo.java
4-65
Exceptions
• When something unexpected happens in a Java
program, an exception is thrown.
• The method that is executing when the exception
is thrown must either handle the exception or
pass it up the line.
• Handling the exception will be discussed later.
• To pass it up the line, the method needs a
throws clause in the method header.
4-66
Exceptions
• To insert a throws clause in a method header, simply add the word throws and the name of the expected exception.
• PrintWriter objects can throw an IOException, so we write the throws clause like this:
public static void main(String[] args) throws IOException{
}
4-67
Appending Text to a File
• To avoid erasing a file that already exists, create a
FileWriter object in this manner:
FileWriter fw =new FileWriter(“Names.txt", true);
• Then, create a PrintWriter object in this manner:
PrintWriter fw = new PrintWriter(fw);
4-68
Specifying a File Location
• On a Windows computer, paths contain backslash
(\) characters.
• Remember, if the backslash is used in a string
literal, it is the escape character so you must use
two of them:
PrintWriter outFile =
new PrintWriter("A:\\PriceList.txt");
C:\\Users\\apeng\\workspace\\outputToFile\\PersonName.txt
public static void main(String[] args) throws IOException {//get a filenameScanner kb = new Scanner(System.in);System.out.println("Enter a filename such as " +
"PersonName.txt : ");String filename = kb.nextLine();//open the file//PrintWriter outputFile = new PrintWriter("Names.txt");//PrintWriter outputFile = new PrintWriter(filename);
//Appending data to the fileFileWriter fwriter = new FileWriter(filename, true);PrintWriter outputFile = new PrintWriter(fwriter);outputFile.println("Chris Janes");outputFile.println("Kathryn Kennedy");outputFile.println("Jean Smith");outputFile.close(); PrintWriter outputFile1 = new PrintWriter(new
FileWriter(filename, true));outputFile1.println(“Peter Pan");outputFile1.close();
}}
4-70
Specifying a File Location
• 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:
PrintWriter outFile = new
PrintWriter("/home/rharrison/names.txt");
An example:
C:\Users\apeng\workspace\outputToFile\PersonName.txt
4-71
Reading Data From a File
• You use the File class and the Scanner class to read
data from a file:
File myFile = new File("Customers.txt");Scanner inputFile = new Scanner(myFile);
Pass the name of the file
as an argument to the
File class constructor.
Pass the File object as an
argument to the Scanner
class constructor.
4-72
Reading Data From a File
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);
• The lines above:
Creates an instance of the Scanner class to read from the keyboard
Prompt the user for a filename
Get the filename from the user
Create an instance of the File class to represent the file
Create an instance of the Scanner class that reads from the file
4-73
Reading Data From a File
• Once an instance of Scanner is created, data can be
read using the same methods that you have used to read
keyboard input (nextLine, nextInt, nextDouble,
etc).
// Open the file.File file = new File("Names.txt");Scanner inputFile = new Scanner(file);// Read a line from the file.String str = inputFile.nextLine();// Close the file.inputFile.close();
4-74
Exceptions
• The Scanner class can throw an IOException
when a File object is passed to its constructor.
• So, we put a throws IOException clause in
the header of the method that instantiates the
Scanner class.
• See Example: ReadFirstLine.java
4-75
Checking for a File’s Existence
//make sure the file exists. If file.exists() method return false,
//indicating the file does not exist.
File file = new File(“Numbers.txt”);
if (!file.exists())
{
System.out.println(“The file Numbers.txt is not found”);
System.exit(0);
}
//Open the file for reading.
Scanner inputFile = new Scanner(file);
…
• See Example: ReadFirstLine.java
4-76
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.
4-77
Detecting the End of a File
• See example: FileReadDemo.java
Next four slides is to deal with output
data to the file and read these data from
this file.
4-78
}else{FileWriter fwriter = new FileWriter(file0, true);PrintWriter outputFile = new PrintWriter(fwriter);outputFile.println("My Comments on the Exponential Penny
Pay Project.");outputFile.println("One more try!");//close the output file. Need this her for outputFile.close(); //for open file to read.
Scanner fileRead = new Scanner(file0);while (fileRead.hasNext()) {String str = fileRead.nextLine();System.out.println("file read: " + str);
}//close the file.fileRead.close();}System.out.println("The program is ended.");
}}
4-79
Output to the file and read from the filepackage fileIOProjectP;import java.util.Scanner;import java.io.*;
public class FileIO {public static void main(String[] args) throws IOException{
String filename; //Filename//Create a Scanner object for keyboard input.Scanner keyboardInput = new Scanner(System.in);
//Get the filename.System.out.print("Enter the filename, " +
"such as wages.txt: ");filename = keyboardInput.nextLine();
//output to the file and read from the fileSystem.out.println("The program is ended.");
}}
4-80
File file0 = new File(filename);//a wrong way to have FileWriter and PrintWriter here.if (!file0.exists()) {
System.out.println("File does not exit.");}else {
FileWriter fwriter = new FileWriter(file0, true);PrintWriter outputFile = new PrintWriter(fwriter);outputFile.println("My Comments on the Exponential Penny Pay
Project.");outputFile.println("One more try!");//close the output file.outputFile.close(); //need this here for open file.
Scanner fileRead = new Scanner(file0);while (fileRead.hasNext()) {
String str = fileRead.nextLine();System.out.println("file read: " + str); }
//close the files.fileRead.close();}System.out.println("The program is ended.");
}
4-81
Generating Random Numbers with the Random Class
• Some applications, such as games and simulations,
require the use of randomly generated numbers.
• The Java API (application programming interfaces) 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();
//Random class constructor, create a Random object.
4-82
Generating Random Numbers with the Random Class
import java.util.Random;
…
//Declare an int variable.
int number;
//Create a Random object.
Random randomNumbers = new Random();
//get a random integer and assign it to number of 10 digits.
number = randomNumbers.nextInt();
//get a random integer with the range of 1 through 10.
number = randomNumbers.nextInt(10)+1;
//get a random integer with the range of -50 through +49.
number = randomNumbers.nextInt(100)-50;
4-83
Some Methods of the Random Class
Method Description
nextDouble() Returns the next random number as a double. The number
will be within the range of 0.0 and 1.0.
nextFloat() Returns the next random number as a float. The number
will be within the range of 0.0 and 1.0.
nextInt() Returns the next random number as an int. The number
will be within the range of an int, which is –2,147,483,648
to +2,147,483,647.
nextInt(int n)
Should write
int n;
nextInt(n)
nextInt(100)
This method accepts an integer argument, n. It returns a random number as an int. The number will be within the
range of 0 to n - 1.
Can be written as nextInt(100) for range [0, 99];
nextInt(100) – 60 for range [-60, 39];
int n = 10; nextInt(n) – n/2;
See example: RollDice.java
4-84
Some Methods of the Random Class
See example: RollDice.java
import java.util.Random;
public class RandomNumberGenerator_5_1_02 {
public static void main(String[] args) {int intNumber;double doubleNumber;int n = 12;
for(int count = 0; count < 10; count++){
Random rand = new Random();intNumber = rand.nextInt(n)-n/2; //range [-6, 5]System.out.println(count + "\t" +
intNumber);}
}}
0 01 42 -43 -44 -35 -16 17 -48 59 -6
4-85
Some Methods of the Random Class
See example: RollDice.java
import java.util.Random;
public class RandomNumberGenerator_5_1_02 {
public static void main(String[] args) {int intNumber;double doubleNumber;int n = 12;
for(int count = 0; count < 10; count++){
Random rand = new Random();//Range [0.0+1.0, 1.0 + 1.0); i.e., [1.0, 2.0).
doubleNumber = rand.nextDouble() + 1.0;
System.out.println(count + "\t" + doubleNumber);
}}
}
0 1.4859759142009537
1 1.2552330132755973
2 1.752354690086619
3 1.1735749253824075
4 1.0658897461299754
5 1.5554388343617656
6 1.7470721933360904
7 1.6203621752503685
8 1.2553601726070869
9 1.2694153737382547
4-86
Some Methods of the Random Class
See example: RollDice.java
import java.util.Random;
public class RandomNumberGenerator_5_1_02 {
public static void main(String[] args) {int intNumber;double doubleNumber;int n = 12;
for(int count = 0; count < 10; count++){
Random rand = new Random();//Range [-0.4, 0.5).
doubleNumber = rand.nextDouble() - 0.5;
System.out.println(count + "\t" + doubleNumber);
}}
}
0 0.1576629888267016
1 -0.27643747955419773
2 -0.010713787727349988
3 0.18216706418850848
4 -0.12342106690756738
5 -0.29396478980704566
6 -0.4954877279193056
7 -0.34704168563781734
8 -0.29613855386752197
9 0.4344266241149557