Java Reference
In-Depth Information
181
Chapter 5 Decisions
C HAPTER G OALS
ȗ
To be able to implement decisions using if statements
ȗ
To understand how to group statements into blocks
ȗ
To learn how to compare integers, floating-point numbers, strings, and objects
ȗ
To recognize the correct ordering of decisions in multiple branches
ȗ
To program conditions using Boolean operators and variables
T
To understand the importance of test coverage
The programs we have seen so far were able to do fast computations and render
graphs, but they were very inflexible. Except for variations in the input, they worked
the same way with every program run. One of the essential features of nontrivial
computer programs is their ability to make decisions and to carry out different
actions, depending on the nature of the inputs. The goal of this chapter is to learn
how to program simple and complex decisions.
181
182
5.1 The if Statement
Computer programs often need to make decisions, taking different actions depending
on a condition.
Consider the bank account class of Chapter 3 . The withdraw method allows you to
withdraw as much money from the account as you like. The balance just moves ever
further into the negatives. That is not a realistic model for a bank account. Let's
implement the withdraw method so that you cannot withdraw more money than
you have in the account. That is, the withdraw method must make a decision:
whether to allow the withdrawal or not.
The if statement is used to implement a decision. The if statement has two parts: a
condition and a body. If the condition is true, the body of the statement is executed.
The body of the if statement consists of a statement:
Search WWH ::




Custom Search