1. Trang chủ
  2. » Công Nghệ Thông Tin

Chapter 4 Loops and Files

118 11 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Loops and Files
Định dạng
Số trang 118
Dung lượng 693,76 KB
File đính kèm Chapter 4 - Loops and Files.rar (604 KB)

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Chapter 4 Chapter 4 Loops and Files 2 Contents 1 The Increment and Decrement Operators 2 The while Loop 3 Using the while Loop for Input Validation 4 The do while Loop 5 The for Loop 6 Running Totals.

Trang 1

Chapter 4

Loops and Files

Trang 2

Contents

1 The Increment and Decrement Operators

2 The while Loop

3 Using the while Loop for Input Validation

4 The do-while Loop

5 The for Loop

6 Running Totals and Sentinel Values

7 Nested Loops

8 The break and continue Statements

Trang 3

Contents

9 Deciding Which Loop to Use

10 Introduction to File Input and Output

11 The Random Class

Trang 4

1 The Increment and Decrement

Operators

Java provides a set of simple unary operators

designed just for incrementing and decrementing variables

Incrementing: increasing by one

Decrementing: decreasing by one

Increment operator ++

Decrement operator

Trang 7

Postfix and Prefix Modes

Trang 8

The Difference between Postfix

and Prefix Modes

The difference is important if these operators

++ and are used in statements that do more

than just increment or decrement

Example:

number = 4;

System.out.println(number++);

This statement does two things:

Calls println method to display

the value of number

Increments number

But which happens first?

Trang 9

The Difference between Postfix

and Prefix Modes

Postfix mode causes the increment to happen

after the value of the variable is used in the

expression

number = 4;

System.out.println(number++);

1 The println method will display 4 and then

2 number will be incremented to 5

number = 4;

System.out.println(number);

number = number + 1;

Trang 10

The Difference between Postfix

and Prefix Modes

The prefix mode causes the increment to happen first

number = 4;

System.out.println(++number);

number will be incremented to 5 and then

The println method will display 5

number = 4;

number = number + 1;

System.out.println(number);

Trang 11

The Difference between Postfix

and Prefix Modes

int x = 1, y;

1.It assigns the value of x to the variable y

2.The variable x is incremented

int x = 1, y;

1.The variable x is incremented

2.It assigns the value of x to the variable y

Trang 12

2 The while Loop

Problem: Write a program to ask a number n, and print “Hello” n times.

Trang 13

2 The while Loop

Trang 14

Test this boolean expression.

If the boolean expression is true, perform these statements.

After executing the body of the loop, start over.

Trang 15

2 The while Loop

Logic of a while loop

boolea n Expressi on

Statement(s) true

false

Trang 17

The while Loop Is a Pretest Loop

The while loop is known as a pretest loop

because it tests its expression before each

The loop will never iterate

if the boolean expression is false to start with.

Trang 18

Infinite Loops

If a loop does not have a way of stopping, it is

called an infinite loop

An infinite loop continues to repeat until the

} This is an infinite loop because it does not contain a that changes the value of the number variable.statement

Each time the boolean expression is

tested, number will contain the value 1.

Trang 19

Infinite Loops

It's also possible to create an infinite loop by

accidentally placing a semicolon after the first line

of the while loop

Trang 21

Programming Style and

the while Loop

Avoid this style of programming

while(number <=5 ) { System.out.println(“Hello”);

number++; }

The programming style

If there is only one statement repeated by the

loop, it should appear on the line after the whilestatement and be indented one additional level

If the loop repeats a block, each line inside the braces should be indented

Trang 22

3 Using the while Loop for Input

Validation

The while loop can be used to create input

routines that repeat until acceptable data is

entered

Input validation is the process of inspecting data given to a program by the user and determining if

it is valid

A good program should give clear instructions

about the kind of input that is acceptable

Do not assume that the user has followed those instructions

Trang 23

If an invalid input is entered, a loop can require

that the user re-enter it as many times as

necessary

Trang 24

Input Validation Logic

Problem: Write a program to ask for a number in the range of 1 through 100

Is the value invalid?

Read the first value

Display an error message. Read anothervalue true

false

Trang 25

Input Validation Logic

input = JOptionPane.showInputDialog(“Enter a number “ +

“ in the range of 1 through 100.”);

Trang 26

4 The do-while Loop

The do-while loop is a posttest loop, which

means its boolean expression is tested after

Trang 27

4 The do-while Loop

The do-while loop's format

do {

Statement1;

Statement2; // Place as many statements here as necessary

}while(BooleanExpression);

The do-while loop must be terminated with a

semicolon

Trang 28

4 The do-while Loop

The do-while loop is a posttest loop

The do-while loop always performs at least one iteration, even if the boolean expression is false

to begin with

Boolea n expressi on

the loop executes at least once.

Trang 29

4 The do-while Loop

Problem: Write a program that averages a series

of three test scores for a student After the

average is displayed, it asks the user if he or she wants to average another set of test scores The program repeats as long as the user enter Y for

yes

The programmer had no way of knowing the

number of times the loop would iterate This is

because the loop asks the user if he or she wants

to repeat the process

This type of loop is known as a user controlled

Trang 30

4 The do-while Loop

Does the user

want

to average another set ?

Get three test scores

true

false Calculate and print the average test score

Trang 31

4 The do-while Loop

Trang 32

4 The do-while Loop

Trang 33

5 The for Loop

In general, there are two categories of loops

Conditional loops

Executes as long as a particular condition exists

An input validation loop

User controlled loop

You have no way of knowing the number of times

it will iterate

Count-controlled loops

Repeats a specific number of times

Trang 34

5 The for Loop

A count controlled loop must process three

elements

It must initialize a control variable to a starting

value

It must test the control variable by comparing it to

a maximum value When the control variable

reaches its maximum value, the loop terminates

It must update the control variable during each

iteration This is usually done by incrementing the variable

Trang 35

The Format of the for Loop

for(Initialization; Test; Update)

Trang 36

The Format of the for Loop

for(Initialization; Test; Update)

● To initialize a control variable

to its starting value

● The first action performed by the loop

● It is only done once.

● A boolean expression that controls the execution of the loop

● As long as this expression is true, the body will repeat.

● The for loop is a pretest loop, so it evaluates the test expression before each iteration.

● It executes at the end of each iteration.

● Typically, this is a statement that increments the loop's control variable.

Trang 38

Sequence of Events in the for

Loop

Here is an example of a simple for loop that

prints “Hello” five times:

int count;

for(count = 1; count <= 5; count++)

System.out.println(“Hello”);

Trang 39

Step 1: Perform the initialization expression

Step 2: Evaluation the test expression If it is true, go to Step

3.

Otherwise, terminate the loop.

Step 3: Execute the body of the loop.

Step 4: Perform the update expression,

then go back to Step 2.

Trang 41

The Control Variable

During the execution of the loop

This variable takes on the values 1 through 5

When the test expression count <= 5 is false, the loop terminates

This variable keeps a count of the number of

iterations, it is often called a counter variable.

The control variable can be used within the body

of the loop

Trang 42

The Control Variable

Print the numbers 1 through 10:

Trang 43

An Example

Write a program to display a table showing the

numbers 1 to 10 and their squares

Trang 44

The for Loop Is a Pretest Loop

The for loop tests its boolean expression before it performs an iteration pretest loop

The following loop will never iterate

Trang 45

Modifying the Control Variable in

the Body of the for Loop

Be careful not to place a statement that modifies the control variable in the body of the for loop All modifications of the control variable should take

place in the update expression

Trang 47

Declaring a Variable in the for

Loop's Initialization Expression

We can declare and initialize the control variable

in the initialization expression of the for loop

Trang 48

Declaring a Variable in the for

Loop's Initialization Expression

When a variable is declared in the initialization

expression of a for loop, the scope of the variable

is limited to the loop

We can not access the variable outside the loop

int number;

for(number = 1; number <= 5; number++)

System.out.println(number);

System.out.println(“number is now “ + number);

for(int number = 1; number <= 5; number++)

System.out.println(number);

1 2 3 4 5 number is now 6

ERROR !

Trang 49

Creating a User Controlled for

Loop

Sometimes we want the user to determine the

maximum value of the control variable in a for

Trang 50

the maximum value

Trang 51

Creating a User Controlled for

Loop

Trang 52

Using Multiple Statements in

Initialization and Update Expr.

It is possible to execute more than one statement

in the initialization expression and the update

Trang 53

Using Multiple Statements in

Initialization and Update Expr.

Trang 55

6 Running Totals and Sentinel

Values

Problem: Calculate a company's total sales over

a period of time by taking daily sales figures as

Trang 56

Running Totals

The total of a series of numbers is sometimes

called a running total

The numbers are gathered and summed during the running of a loop

A running total is a sum of numbers that

accumulates with each iteration of a loop

The variable used to keep the running total is

called an accumulator

Trang 57

Increment count Allow the user to enter

the number of days

Trang 58

6 Running Totals and Sentinel

Values

Trang 60

Using a Sentinel Value

Problem: Write a program to calculate the total

points earned by a soccer team has earned over a series of games The user enters a series of point values, and then -1 to signal the end of the list

Input: The user enters a series of point values, -1 when finished

Output: Total points

A special value signals the end of the list

The value -1 was chosen for the special value in this program because it is not possible for a team

to score negative points

Trang 61

Using a Sentinel Value

Number of points != -1 true

false

Add points to totalPoints number of pointsGet the next

Assign 0 to the

accumulator totalPoints

Get the first number of points

Trang 62

Using a Sentinel Value

Sometimes the user has a very long list of input values, and doesn't know the exact number of

When the user enters the sentinel value, the loop terminates

Trang 63

Using a Sentinel Value

Trang 64

Using a Sentinel Value

Trang 66

7 Nested Loops

Trang 67

7 Nested Loops

A loop that is inside another loop is called a

nested loop

A few points about nested loops:

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

Trang 68

The loop stops and the program jumps to the

statement immediately following the loop

The continue statement causes a loop to stop its current iteration and begin the next one

All the statements in the body of the loop that

appear after it are ignored, and the loop prepares for the next iteration

Trang 69

8 The break and continue

Statements

Trang 70

9 Deciding Which Loop to Use

The while loop

It 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

The do-while loop

It is a posttest loop

It is ideal in situations where you always want the

Trang 71

9 Deciding Which Loop to Use

The for loop

It is a pretest loop that has built-in expressions for initializing, testing, and updating

Very convenient to use a loop control variable as

a counter

It is ideal in situations where the exact number of iterations is known

Trang 73

To write data to a file

Trang 74

10 Introduction to File Input and

Output

Data may be saved in a file, which is usually

stored on a computer's disk

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

Trang 75

Input Files and Output Files

An input file is a file that a program reads data

from

It is called an input file because the data stored in

it serves as input to the program

An output file is a file that a program writes data

to

It is called an output file because the program

stores output in the file

Trang 76

Input Files and Output Files

The file is opened

The program reads data from the opened

file.

The file is closed Input file

The file is opened

The program writes data

to the opened file.

The file is closed Output file

Trang 77

Text Files and Binary Files

A 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

The file may be opened and viewed in a text

Trang 78

Writing Data to a File

To write data to a file, you must create objects

from the following classes:

FileWriter

This class allows you to open a file for writing and establishing a connection with it It provides only basic functionality for writing data to the file

Trang 79

Writing Data to a File

Open a file and establish a connection with it:

FileWriter fwriter = new FileWriter(“StudentData.txt”);

Creates an empty file named StudentData.txt and

establishes a connection between the file and the FileWriter object

The file will be created in the current folder

If the file opened with the FileWriter object

already exists, it will be erased and an empty file with the same name will be created

Trang 80

Writing Data to a File

We may also pass a reference to a

String object as an argument to the FileWriter

Trang 81

Writing Data to a File

Creating a PrintWriter object

FileWriter fwriter = new FileWriter(“StudentData.txt”);

PrintWriter outFile = new PrintWriter(fwriter);

Using print and println methods to write data

to a file

FileWriter fwriter = new FileWriter(“StudentData.txt”);

PrintWriter outFile = new PrintWriter(fwriter);

outputFile.println(“Jim”);

Trang 82

Writing Data to a File

When the program is finished writing data to the file, it must be closed

FileWriter fwriter = new FileWriter(“StudentData.txt”);

PrintWriter outFile = new PrintWriter(fwriter);

outputFile.println(“Jim”);

outputFile.close();

Trang 83

Writing Data to a File

The program should always close files when it's finished with them

When a program writes a file to a file, data is first written to the file's buffer When the buffer is filled, all information stored there is written to the file

The close method writes any unsaved data

remaining in the file's buffer

Once a file is closed, the connection between it

and the FileWriter object is removed In order

to perform further operations on the file, it must be opened again

Trang 84

The PrintWriter Class's

println Method

The PrintWriter class's println method

writes a line of data to a file

Create a file named StudentData.txt and write two

students' first names and their test scores to the

file:

FileWriter fwriter = new FileWriter(“StudentData.txt”);

PrintWriter outFile = new PrintWriter(fwriter);

Ngày đăng: 27/09/2022, 22:17

w