Chapter 4 Loops and Files (reading)
The while loop has two important parts:
(1) a boolean expression that is tested for a true or false value (2) a statement or block of statements that is repeated as long as the expression is true.
____ and________ are operators that add and subtract one from their operands.
++, −−
How many times will "Hello World" be printed in the following program segment? int count = 10; while (count < 1) { System.out.println("Hello World"); count++; }
0 times
What will the following program segments display? c) x = 2; System.out.println(--x);
1 (the decrement happened before display x)
A count-controlled loop must possess three elements:
1. It must initialize a control variable to a starting value. 2. It must test the control variable by comparing it to a maximum value. When the control variable reaches its maximum value, the loop terminates. 3. It must update the control variable during each iteration. This is usually done by incrementing the variable.
In general, there are three steps that are taken when a file is used by a program:
1. The file must be opened. When the file is opened, a connection is created between the file and the program. 2. Data is then written to the file or read from the file. 3. When the program is finished using the file, the file must be closed.
What will the following program segments display? a) x = 2; y = x++; System.out.println(y);
2 ( 2 is assigned to y before x increment)
What will the following program segments display? b) x = 2; System.out.println(x++);
2 (the display x before x increment)
What will the following program segments display? d) x = 8; y = x--; System.out.println(y);
8 ( x is assigned to y before x decrement)
_________to a file means writing new data to the end of the data that already exists in the file.
Appending
4.16 What is the difference between an input file and an output file?
Data is read from an input file, and data is written to an output file.
You can also use the Scanner class to read input from a file. Instead of passing System.in to the Scanner class constructor, you pass a reference to a _______object.
File
You create a Scanner object and pass a reference to the ____object as an argument to the constructor.
File
You create a _______object and pass the name of the file as a string to the constructor.
File
4.20 What classes do you use to read data from a file?
File and Scanner
4.21 Write code that does the following: opens a file named MyName.txt, reads the first line from the file and displays it, and then closes the file.
File file = new File("MyName.txt"); Scanner inputFile = new Scanner(file); if (inputFile.hasNext()) { String str = inputFile.nextLine(); System.out.println(str); } inputFile.close();
To append data to an existing file, you first create an instance of the _______class. You pass two arguments to the FileWriter constructor: a string containing the name of the file, and the boolean value true.
FileWriter
when you create a _______object and opens a file for writing, Any data written to the file will be appended to the file's existing contents. (If the file does not exist, it will be created.)
FileWriter
4.7 Name the three expressions that appear inside the parentheses in the for loop's header.
Initialization, test, and update.
4.25 Assume x is an int variable, and rand references a Random object. What does the following statement do? x = rand.nextInt(100);
It assigns the variable x a random integer in the range 0 through 99.
4.26 Assume x is an int variable, and rand references a Random object. What does the following statement do? x = rand.nextInt(9) + 1;
It assigns the variable x a random integer in the range 1 through 9
4.24 Assume x is an int variable, and rand references a Random object. What does the following statement do? x = rand.nextInt();
It assigns the variable x a random integer in the range −2,147,483,648 to +2,147,483,647.
4.27 Assume x is a double variable, and rand references a Random object. What does the following statement do? x = rand.nextDouble();
It assigns the variable x a random number in the range 0.0 to 1.0.
4.3 How many times will "I love Java programming!" be printed in the following program segment? int count = 0; while (count < 10) System.out.println("I love Java programming!);
Loop will execute infinitely
_______mode causes the increment to happen after the value of the variable is used in the expression. In
Postfix
____ mode, however, causes the increment to happen first.
Prefix
4.18 What class do you use to write data to a file?
PrintWriter
The ______class allows you to open a file for writing. It also allows you to write data to the file using the same print and println methods that you have been using to display data on the screen.
PrintWriter
To write data to a file you will create an instance of the _____class.
PrintWriter
when you create a FileWriter object and opens a file for writing, You still need to create a ____object so you can use the print and println methods to write data to the file.
PrintWriter
4.19 Write code that does the following: opens a file named MyName.txt, writes your first name to the file, and then closes the file.
PrintWriter outputFile = new PrintWriter("MyName.txt"); outputFile.println("my name"); outputFile.close();
file. To write data to a file, you can use the _______class and, optionally, the _______class.
PrintWriter, FileWriter
Java provides the _______class that you can use to generate random numbers.
Random
4.4 Write an input validation loop that asks the user to enter a number in the range of 10 through 24.
Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number in the range of 10 - 24: "); number = keyboard.nextInt(); while (number < 10 || number > 24) { System.out.println("That number is not in the range."); System.out.print("Enter a number in the range of 10 - 24: "); number = keyboard.nextInt(); }
4.13 Write a for loop that repeats seven times, asking the user to enter a number. The loop should also calculate the sum of the numbers entered.
Scanner keyboard = new Scanner(System.in); int number = 0, total = 0; for (int i = 1; i <= 7; i++) { System.out.print("Enter a number: "); number = keyboard.nextInt(); total += number; }
4.5 Write an input validation loop that asks the user to enter 'Y', 'y', 'N', or 'n'.
String input; Scanner keyboard = new Scanner(System.in); System.out.print("Enter Y, y, N, or n: "); input = keyboard.nextLine(); ch = input.charAt(0); while (ch != 'Y' && ch != 'y' && ch != 'N' && ch != 'n') { System.out.println("Try again."); System.out.print("Enter Y, y, N, or n: "); input = keyboard.nextLine(); ch = input.charAt(0); }
4.6 Write an input validation loop that asks the user to enter "Yes" or "No".
String str; Scanner keyboard = new Scanner(System.in); System.out.print("Enter Yes or No: "); str = keyboard.nextLine(); while ((!str.equals("Yes")) && (!str.equals("No"))) { System.out.print("Please enter Yes or No: "); str = keyboard.nextLine(); }
4.14 In the following program segment, which variable is the loop control variable (also known as the counter variable) and which is the accumulator? int a, x = 0, y = 0; while (x < 10) { a = x * 2; y += a; x++; } System.out.println("The sum is " + y);
The variable x is the loop control variable and y is the accumulator.
4.22 You are opening an existing file for output. How do you open the file without erasing it, and at the same time make sure that new data that is written to the file is appended to the end of the file's existing data?
You create an instance of the FileWriter class to open the file. You pass the name of the file (a string) as the constructor's first argument, and the boolean value true as the second argument. Then, when you create an instance of the PrintWriter class, you pass a reference to the FileWriter object as an argument to the PrintWriter constructor. The file will not be erased if it already exists and new data will be written to the end of the file.
4.15 Why should you be careful when choosing a sentinel value?
You should be careful to choose a value that cannot be mistaken as a valid input value.
4.9 What will the following program segments display? a) for (int count = 0; count < 6; count++) System.out.println(count + count); b) for (int value = -5; value < 5; value++) System.out.println(value); c) int x; for (x = 5; x <= 14; x += 3) System.out.println(x);
a) 0 2 4 6 8 10 b) -5 -4 -3 -2 -1 0 1 2 3 4 c) 5 8 11 14 17
4.8 You want to write a for loop that displays "I love to program" 50 times. Assume that you will use a control variable named count. a) What initialization expression will you use? b) What test expression will you use? c) What update expression will you use? d) Write the loop.
a) count = 1 b) count <= 50 c) count++ d) for (int count = 1; count <= 50; count++) System.out.println("I love to program");
The variable used to accumulate the total of the numbers is called an ____________. It is often said that the loop keeps a running total because it accumulates the total as it reads each number in the series.
accumulator
The variable used to keep the running total is called an ________.
accumulator
If there is only one statement repeated by the loop, it should appear on the line ________the while statement and be indented one additional level. The statement can optionally appear inside a set of braces.
after
A _______file contains data that has not been converted to text.
binary
The ______statement causes a loop to terminate early.
break
you should avoid using the _____statement in a loop when possible.
break
A _____is a small "holding section" of memory.
buffer
Your application should always close files when finished with them. This is because the system creates one or more _____when a file is opened.
buffers
To close the file use the PrintWriter class's ______method.
close
When finished writing to the file, you use the PrintWriter class's close method to _____the file.
close
When finished writing to the file, you use the Scanner class's _____method to close the file.
close
A ________loop executes as long as a particular condition exists.
conditional
When you write a _________loop, you have no way of knowing the number of times it will iterate.
conditional
In general, there are two categories of loops: _________loops and __________loops.
conditional, count-controlled
The _______statement causes the current iteration of a loop to end immediately.
continue
The ______statement should also be avoided. Like the break statement, it bypasses the loop's logic and makes the code difficult to understand and debug.
continue
The ____statement causes a loop to stop its current iteration and begin the next one.
continue
When ______is encountered, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration.
continue
A loop that repeats a specific number of times is known as a count-________loop.
controlled
A _______is an item that separates other items.
delimiter
In addition to separating the contents of a file into lines, the newline character also serves as a ______.
delimiter
The _______loop is a posttest loop, which means its boolean expression is tested after each iteration.
do-while
The _______loop is a posttest loop. It is ideal in situations where you always want the loop to iterate at least once.
do-while
This type of loop is known as a user controlled loop, because it allows the user to decide the number of iterations.
do-while
You should use the _____ loop when you want to make sure the loop executes at least once.
do-while
the_________loop always performs at least one iteration, even if the boolean expression is false to begin with.
do-while
If your program asks the user to enter a path into a String object, which is then passed to the PrintWriter or FileWriter constructor, the user does not have to enter ______backslashes.
double
You only need to use _____backslashes if the file's path is in a string literal.
double
Java allows you to substitute forward slashes for backslashes in a Windows path. For example, the path "C:\\MyData\\Data.txt" could be written as "C:/MyData/Data.txt". This ______the need to use double backslashes.
eliminates
If the file that you are opening with the PrintWriter object already exists, it will be _____and an empty file by the same name will be created.
erased
After you create a File object representing the file that you want to open, you can use the File class's ______method to determine whether the file exists.
exists
The________method returns true if the file exists, or false if the file does not exist.
exists
An important characteristic of the while loop is that the loop will never iterate if the boolean expression is______ to start with.
false
The ______loop is a pretest loop that has built-in expressions for initializing, testing, and updating. These expressions make it very convenient to use a loop control variable as a counter. The for loop is ideal in situations where the exact number of iterations is known.
for
The _____loop is ideal for performing a known number of iterations.
for
4.12 Write a for loop that displays every fifth number, zero through 100.
for (int i = 0; i <= 100; i += 5) System.out.println(i);
4.10 Write a for loop that displays your name 10 times.
for (int i = 1; i <= 10; i++) System.out.println("my name");
4.11 Write a for loop that displays all of the odd numbers, 1 through 49.
for (int i = 1; i <= 49; i += 2) System.out.println(i);
Call the Scanner class's ______method to determine whether there is more data to read from the file. If the method returns true, then there is more data to read. If the method returns false, you have reached the end of the file.
hasNext
The Scanner class has a method named ________that can be used to determine whether the file has more data that can be read.
hasNext
4.17 What import statement will you need in a program that performs file operations?
import java.io.*;
The Java API provides a number of classes that you will use to work with files. To use these classes, you will place the following import statement near the top of your program:
import java.io.*;
when writing a program that writes data to a file: You need the _____ ____ __ statement in the top section of your program.
import java.io.*;
If a loop does not have a way of stopping, it is called an _______loop as it continues to repeat until the program is interrupted.
infinite
An _____file is a file that a program reads data from.
input
It is called an ______file because the data stored in it serves as input to the program.
input
A _____is a control structure that causes a statement or group of statements to repeat.
loop
To get the total number of iterations of a nested loop, _______the number of iterations of all the loops.
multiply
You create a PrintWriter object and pass the _______ of the file as a string to the constructor.
name
A loop that is inside another loop is called a ______loop.
nested
You use the Scanner class's ________method to read a line from the file. The method returns the line of data as a string. To read primitive values, use methods such as nextInt, nextDouble, and so forth.
nextLine
number−− is pronounced "___ ____ ___."
number minus minus
The expression number++ is pronounced "____ ____ _____,"
number plus plus
To increment a value means to increase it by____
one
to decrement a value means to decrease it by ___.
one
An ____file is a file that a program writes data to.
output
It is called an _____file because the program stores output in the file.
output
A ___ ____ is a sum of numbers that accumulates with each iteration of a loop.
running total
Notice there is no ________at the end of the loop header. Like the if statement, the while loop is not complete without the conditionally executed statement that follows it.
semicolon
The do-while loop must be terminated with a ______.
semicolon
A _____is a value that signals when the end of a list of values has been reached.
sentinel
A _____value is a special value that cannot be mistaken as a member of the list, and signals that there are no more values to be entered
sentinel
A _____file contains data that has been encoded as text, using a scheme such as Unicode.
text
In general, there are two types of files: ___ ___ ___
text and binary.
4.23 What clause must you write in the header of a method that performs a file operation?
throws IOException
Because we have not yet learned how to respond to exceptions, any method that uses a PrintWriter object must have a___ _____clause in its header.
throws IOException
In addition, any method that calls a method that uses a PrintWriter object should have a ____ _____ clause in its header
throws IOException
The FileWriter class also ___ ___ ___ if the file cannot be opened for any reason.
throws an IOException
When an unexpected event occurs in a Java program, it is said that the program ___ ____ ____
throws an exception
To allow a method to rethrow an exception that has not been dealt with, you simply write a __ _____ in the method header.
throws clause
when you provide a path in a string literal, and the path contains backslash characters, you must use ____backslash characters in the place of each single backslash character.
two
The throws clause must indicate the ______of exception that might be thrown.
type
Input ______is the process of inspecting data given to a program by the user and determining whether it is valid.
validation
It's also possible to create an infinite loop by accidentally placing a semicolon after the first line of the ______loop.
while
The ______loop is a pretest loop. It is ideal in situations where you do not want the loop to iterate if the condition is false from the beginning. It is also ideal if you want to use a sentinel value to terminate the loop.
while
The _____loop is especially useful for validating input. If an invalid value is entered, a loop can require that the user reenter it as many times as necessary.
while
The______loop is known as a pretest loop, which means it tests its expression before each iteration.
while
____ ___ _____ consists of the key word while followed by the BooleanExpression enclosed in parentheses.
while loop header
Java has three looping control structures: the ____ loop, the ___ ___loop, and the ____loop.
while, do-while, for
You use the PrintWriter class's print and println methods to _____data to the file.
write
The close method ____any unsaved data remaining in the file buffer.
writes