Java Reference
In-Depth Information
Chapter 5
Program Logic and
Indefinite Loops
Introduction
5.1 The while Loop
A Loop to Find the Smallest
Divisor
The chapter begins by examining a new construct called a while loop
that allows you to loop an indefinite number of times.The while loop
will allow you to solve a new class of programming problems in which you
don't know in advance how many times you want a loop to execute. For
example, game-playing programs often involve while loops because it is
not possible to know beforehand how the user will play the game.
Because we will be exploring game programs, we will also explore how to
generate random numbers inside a Java program. We will also explore
another class of algorithms known as fencepost algorithms that occur
often in loop-programming tasks.
Random Numbers
Simulations
The do/while Loop
5.2 Fencepost Algorithms
Sentinel Loops
Fencepost with if
5.3 The boolean Ty p e
Logical Operators
Short-Circuited Evaluation
boolean Variables and Flags
Boolean Zen
The chapter then discusses the fourth primitive type that we are going to
examine in detail, boolean . The boolean type is used to store logical
(true/false) information. Once you understand the details of the boolean
type, you will be able to write complex loops involving multiple tests.
Negating Boolean Expressions
5.4 User Errors
Scanner Lookahead
Handling User Errors
5.5 Assertions and Program
Logic
Next, we'll briefly examine the important topic of handling user errors.
Reasoning about Assertions
The chapter concludes with a discussion of assertions. Using assertions,
you can reason about the formal properties of programs (what is true at
different points in program execution).
A Detailed Assertions Example
5.6 Case Study: NumberGuess
Initial Version without Hinting
Randomized Version with
Hinting
Final Robust Version
301
 
Search WWH ::




Custom Search