Chapter 4 Loops and Files

Ace your homework & exams now with Quizwiz!

Conditional Loop

Execute as long as a particular condition exists. For example, an input validation loop executes as long as the input values is invalid. When you write a conditional loop, you have no way of knowing the number of times it will iterate.

Update Expression

It executes at the end of each iteration. Typically, this is a statement that increments the loop's control variable. *Ex* count++

Initialization Expression

It is normally used to initialize a control variable to its starting value. This is the first action performed by the loop, and it is done only once. *Ex* count = 1

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: *Example* PrintWriter outFile = new PrintWriter("A:\\PriceList.txt");

Reading Lines form 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). *Example* // 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()

Postfix and Prefix Modes

Postfix mode means the operator is placed after the variable. Prefix mode means the operator is placed before the variable. Examples: number++; ++number; * Both Work*

Random Class

Random numbers are used in a variety of applications. Java provides the Random class that you can use to generate random numbers. 1) This class is part of the java.util package, so any program that uses it will need an import statement such as: 2) You can create an object from the Random class with a statement such as this: 3) Next, you can call its nextInt method to get a random integer number. *Example* import java.util.Random; Random randomNumbers = new Random(); int number number = randomNumbers.nextInt

Intro. to File Input and Output

The Java API provides several classes that you can use for writing data to a file and reading data from a file. To write data to a file, you can use *PrintWriter* class and, optionally, the *FileWriter* class. To read data from a file, you can use the *Scanner* class and the *File* class.

The do-while Loop

The do-while loop is a posttest loop, which means its boolean expression is tested after it has completed an iteration. As a result, the do-while loop always performs at least one iteration, even if the boolean expression is false to begin with. This differs from the behavior of a while loop, which you recall is a pretest loop. * For Example * The following while loop the println will not execute at all: int x = 1; while (x<0) System.out.println(x);

Loop Header

The first line of the for loop. * Ex * for (Initialization; Test; Update) for (count = 1; count <= 5; count++)

The for Loop

The for loop is ideal for performing a known number of iterations. It is specifically designed to initialize, test, and update a loop control variable. * Example of for loop that prints "Hello" 5x * for (count = 1; count <= 5; count++) System.out.println("Hello");

Input Validation

The process of inspecting data given to a program by the user and determining whether it is valid.

Accumulator

The variable used to keep the running total (accumulate the total of the numbers). * The first step is to set the accumulator variable to 0. This is a critical step! *

Using while loop for input validation

The while loop can be used to create input routines that repeat until acceptable data is entered. * Example * while (number < 1 || number > 100) { input = JOptionPane.showInputDialog("Invalid input. Enter a number in the range of 1 through 100."); number = Integer.parseInt(input); }

Pretest Loop

The while loop is a pretest loop, which means it tests its expression before each iteration. An important characteristic of the while loop is that the loop will never iterate if the boolean expression is false to start with.

Test Expression

This is a boolean expression that controls the execution of the loop. As long as this expression is true, the body of the for loop will repeat. The for loop is a pretest loop, so it evaluated the test expression before each iteration. *Ex* count <= 5

FileWriter Class

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); WHY? So you can use the print and println methods to write data to the file.

Increment and Decrement Operators

To increment a value means to increase it by one and to decrement a value means to decrease it by one. Examples: int number = 4; number++; // number is 5 now number--;// number is 4 now

The File class's exists method

Use the file class's exists method to determine whether a file exists. The method returns true if the file exists and false if the file does not exist. *Example* File file = newFile("Numbers.txt"); if (!file.exists()) { System.out.println(" The file Numbers.txt is not found"); System.exit(0); }

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. To insert a throws clause in a method header, simply add the word throws and the name of the expected exception. * Example * public static void main(String[] args) *throws IOException*

Reading Data from a File

You use the File class and the Scanner class to read data from a file: *Example* 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. When finished reading use the Scanner class's close method: Ex. inputFile.close();

Import Statement for coding with files

import java.io.*;

Input File

A file that a program reads data from.

Output File

A file that a program writes data to. It is called an output file because the program stores output in the file.

The While Loop

A loop is part of a program that repeats. The while loop has two important parts: (1) a boolean expression that is tested for a true or false value; and (2) a statement or block of statements that is repeated as long as the loop expression is true. Don't forget the braces w/ block of statements. Each repetition of a loop is known as an iteration

Nested Loop

A loop that is inside another loop. - An inner loop goes through all of its iterations for each iteration of an outer loop. - Inner loops complete their iterations before outer loops do - To get the total number of iterations of a nested loop, multiply the number of iterations of all the loops

Count-controlled Loop

A loop that repeats a specific number of times. For example, if a loop asks the user to enter the sales amount for each month in the year, it will iterate 12 times. In essence, the loop counts to 12 and asks the user to enter a sales amount each time it makes a count. * A Count-controlled Loop must Possess 3 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 incrementing the variable.

Running Total

A running total is a sum of numbers that accumulates with each iteration of a loop. It is said the loop keeps a running total because it accumulates the total as it reads each number in the series.

A Sentinel Value

A special value that cannot be mistaken as a member of the list, and signals that there are no more values to be entered. When the user enters the sentinel value, the loop terminates.

User Controlled Loop

Allows the user to decide the number of iterations by asking the user whether he/she wants to repeat the process.

PrintWriter 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. *Example* PrintWriter outputFile = new PrintWriter("StudentData.txt); This statement will create an empty file named StudentData.txt and establish a connection b/w it an the PrintWriter object that is referred by ouputFile. When the program is finished writing data to the file, it must close the file using the PrinterWriter class's close method. *Example* outputFile.close();

The Scanner class's hasNext() method

Call the Scanner class's hasNext() method to determine whether there is more data to read from the file. If the method returns true, then there id more data to read. If the method returns false, you have reached the end of the file. *Example* while ( inputFile.hasNext() ) { String str = inputFile.nextLine(); System.out.println(str); } inputFile.close();

Break Statement

Causes a loop to terminate early. When it is encountered, the loop stops and the program jumps to the statement immediately following the loop.

Continue Statement

Causes the current iteration of a loop to end immediately and begin the next one. When it 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.

Text File

Contains data that has been encoded as text, using a scheme such as Unicode. Even if the file contains numbers, those numbers are stored in the file as a series of characters. As a result, the file may be opened and viewed in a text editor such as Notepad.

Binary File

Contains data that has not been converted to text. As a consequence, you cannot view the contents of a binary file with a text editor.


Related study sets

conceptual problems ch.17 accy 304

View Set

Chapter 5 Business mission and strategy

View Set

Coagulase and Clumping Factor Test

View Set