Java Reference
In-Depth Information
5.5 Assertions and Program Logic
Logicians concern themselves with declarative statements called assertions.
Assertion
A declarative sentence that is either true or false.
The following statements are all assertions:
•2
2 equals 4.
The sun is larger than the Earth.
x
45.
It was raining.
The rain in Spain falls mainly on the plain.
The following statements are not assertions (the first is a question and the second
is a command):
How much do you weigh?
Take me home.
Some assertions are true or false depending upon their context:
x
45. (The validity of this statement depends on the value of x .)
It was raining. (The validity of this statement depends on the time and location.)
You can pin down whether they are true or false by providing a context:
When x
13, x
45.
On July 4, 1776, in Philadelphia, it was raining.
To write programs correctly and efficiently, you must learn to make assertions
about your programs and to understand the contexts in which those assertions will be
true. For example, if you are trying to obtain a nonnegative number from the user,
you want the assertion “Number is nonnegative” to be true. You can use a simple
prompt and read:
System.out.print("Please give me a nonnegative number——> ");
double number = console.nextDouble();
// is number nonnegative?
But the user can ignore your request and input a negative number anyway. In fact,
users often input values that you don't expect, usually because they are confused. Given
 
Search WWH ::




Custom Search