Chapter 5. Decisions
CHAPTER GOALS
To be able to implement decisions using if statements
To effectively group statements into blocks
To learn how to compare integers, floating-point numbers, strings, and objects
To correctly order decisions in multiple branches and nested branches
To program conditions using Boolean operators and variables
T To be able to design tests that cover all parts of a program
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.
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. ...
Get Big Java, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.