Download Programming with Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming with Java
1
Chapter 6
Decisions and Conditions
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
2
Objectives
•
•
•
•
•
•
•
•
Read and create flowcharts that show the logic of a selection
process.
Use if statements to control the flow of logic.
Understand and use nested ifs.
Evaluate conditions using the relational operators.
Combine conditions using the logical operators.
Perform validation on numeric fields.
Determine the event that caused the actionPerformed method to
be called.
Understand the precedence and relationship of assignment,
arithmetic, logical, and relational operators.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
3
Decision Statements
•
The decision statements are one of the most powerful statements
because it has the ability to make decisions and take alternate
courses of action based on the outcome.
•
The decision made by the computer is formed as a question: Is
the given condition true or false? If it is true do one thing and if
it is false do something else.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
4
The if Statement-General Form
if (condition)
statement;
[else
statement]
if (condition)
{
statement(s);
}
[else
{
statement(s);
}]
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
5
The if Statement-Examples
if (fltHours > 40.0f)
{
CalculateOvertime();
}
if (intGrade >= 70)
{
lblGrade.setText("Pass");
}
else
{
lblGrade.setText("No Pass");
}
if (intAge < 12)
CalculateDiscount();
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
6
Decision Statements
•
•
The curly braces become important when you have more than
one statement after the if or else statement.
Let us look at Examples:
intAge = 12
Example 1:
if( intAge < 12)
CalculateDiscount();
DisplayDiscount();
Example 2:
if( intAge < 12)
{
CalculateDiscount();
DisplayDiscount();
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
7
Decision Statements Continued
• It is good programming practice to have curly brackets regardless
of the number of statements you have in the if or else clauses.
• If you place a semicolon after the if statement. You will not get a
syntax error but the if statement will be terminated after the
condition.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
8
Conditions
•
You can form conditions with numeric variables and constants,
character (char) variables and constants, and arithmetic
expressions.
•
Note that the relational operator for equality is = = signs, as one
equal sign is an assignment operator.
•
If you use an assignment operator in a condition you will
receive an error as the condition has to evaluate to a boolean.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
9
Sample Comparison Section
Sample Comparisons
int intAlpha = 5;
int intBravo = 4;
int intCharlie = -5; `4
Condition
intAlpha = = intBravo
Evaluates
false
intCharlie < 0
true
intBravo > intAlpha
false
intCharlie <= intBravo
true
intAlPha >= 5
true
intALpha != intCharlie
true
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
10
Comparing Data
• The comparison of one character to another is based on the ASCII
code.
• The comparison of a character with or without single quotes
produces different evaluations.
• For example : chrSex = = ‘F’ // this will compare to the letter F.
• For example : chrCode != ‘\0’ // this will compare with a null
character and not 0.
• For example : chrCode = = ‘9’ // this will compare to the digit 9.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
11
Comparing Data Continued
• For example : chrCode = = ‘9’ // this will compare to the ASCII
code 9 which is a tab character.
• For example : char chrQuestionMark = ‘?’, chrExclamation = ‘!’;
The condition (chrQuestionMark < chrExclamation)
will evaluate to false.
chrQuestionMark has the ASCII value of 63
chrExclamation has the ASCII value of 33
• If you wanted to compare individual characters in a string, you can
by obtaining a single character with the charAt method.
• For example : (strName.charAt(0) = = ‘A’)
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
12
Comparing Numeric Wrapper
Classes
•
When using numeric wrapper classes you will have to use the
equals method to compare the numeric wrapper objects.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
13
Comparing Strings
•
You can use methods of the String class to compare String
objects to String objects or string literals enclosed in quotes.
•
If you are testing for equality, you can use the equals method or
equalsIgnoreCase method.
•
If you wish to compare strings in alphabetical order then you
need to use the compareTo method. It will compare greater than
or less than.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
14
The Equals Method
•
The string class equals method returns true if the strings are the
same and false if they differ.
•
As soon as a character in one string is not equal to the
corresponding character in the second string, the comparison is
terminated, and condition returns false.
•
Let’s look at an example :
String strName = new String(“Joan”);
String strName = new String(“John”);
•
(strName.equals(strName2)) will evaluate to false because a has
a lower ranking than h in John.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
15
The equalsIgnoreCase Method
•
Let’s look at an example:
String strName = new String(“joan”);
String strName2 = new String(“JOAN”);
(strName.equals(strName2));
//evaluates to false
(strName.equalsIgnoreCase(strName2));
// evaluates to true
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
16
The compareTo Method
•
The compareTo method returns an integer with one of three
possible values.
•
If strString1 is greater than strString2, a positive value is
returned.
•
If strString2 is greater than strString1, a negative value is
returned.
•
To use this method effectively, you can set up a condition using
the return value and relational operator.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
17
The compareTo Method Continued
•
(strString1.compareTo(strString2) = = 0) //Are the strings
equal
•
(strString1.compareTo(strString2) ! = 0) //Are the strings
different
•
(strString1.compareTo(strString2) > 0) //Is strString1 greater
than strString2
•
What happens when one word is shorter than the other? How
does it compare?
•
The shorter word is padded with blanks to have the same length
and the comparison begins.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
18
ASCII Code
Code
Value
Code
Value
Code
Value
0
Null
38
&
60
<
8
backspace
39
'
61
=
9
Tab
40
(
62
>
10
Linefeed
41
)
63
?
12
FormFeed
42
*
64
@
13
Carriage
Return
43
+
65-90
A-Z
27
Escape
44
,
91
[
32
Space
45
-
92
\
33
!
46
.
93
]
34
“
47
/
94
^
35
#
48-57
0-9
95
-
36
$
58
:
96
`
37
%
59
;
97-122
a-z
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
19
The Logical Operators
•
You can test multiple conditions using logical operators to
combine conditions.
Logical Operators
Logical Operator
Meaning
Evaluates
&&
And
Both conditions must
be true for the entire
condition to be true.
||
Or
Either condition or
both conditions must
be true for the entire
condition to be true.
!
Not
Reverse the truth of a
condition.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
20
Precedence of Logical Operators in
Compound Conditions
•
&& operator has higher precedence than the || operator and the
conditions are read left to right.
•
To alter the order of evaluation, use parentheses.
•
Beware of smart compilers, once they have determined that the
condition is false, they will not evaluate the rest of the condition.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
21
Nested If Statements
A. Let us look at example of nested if:
if(intAge < 21)
{
if(chrSex = = “M”)
strCategory = “BOY”;
else(chrSex = = “F”)
strCategory = “GIRL”;
}
else
{
strCategory = “ADULT”;
}
McGraw-Hill/Irwin
A. First Method:
if (intTemp <= 32)
{
lblComment.setText("Freezing");
}
else
{
if (intTemp > 80)
{
lblComment.setText("Hot");
}
else
{
lblComment.setText("Moderate);
}
}
B. Second Method:
if (intTemp <= 32)
{
lblComment.setText("Freezing");
}
else if (intTemp > 80)
{
lblComment.setText("Hot");
}
else
{
lblComment.setText("Moderate);
}
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
22
Flowcharting a Nested if Statement
intTemp>32?
True
lblComment.Capt
ion = “Freezing”
False
intTemp>80?
True
lblComment.Capt
ion = “Moderate”
McGraw-Hill/Irwin
False
lblComment.Caption
= “Hot”
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
23
Conditional Operator
•
You can write decisions using Java’s conditional operator
which is the shortcut version of if then else.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
24
The Conditional Operator –
General Format
(condition) ? TrueResult : FalseResult
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
25
The Conditional Operator Examples
fltRate = (fltSales < 10000f) ? .05f : .1f;
fltCommission = (fltSales < 10000f) ? fltSales * .05f : fltSales * .1f;
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
26
Validating User Input
•
Checking to verify the data entered is correct is called validation.
•
Validation may include making sure that data is numeric,
checking for specific values, checking a range of values, or
making sure that the required item is entered.
•
We separate the user interface code form the code to handle
processing.
•
We check for the input data in the applet class and the business
rules in the processing class.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
27
Checking for Business Rules
•
Often you must check an input value to make sure that it follows
business rules.
•
Business rules may be a rate of pay, a check amount, or the
amount of hours worked do not exceed a certain limit.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
28
Validating in a Class
•
So for invalid data the instance variables are set to negative 1.
•
This is one way of indicating bad data, the other is checking
with a boolean variable.
•
In the applet that instantiates the processing class, you can check
for the instance variables if they passed the validation, to
continue processing or not.
•
Using this technique, you properly separate the UI components
for the business rules and calculations.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
29
Passing Variables as Arguments of
a Method
•
When you set up a class, you need to decide whether to assign
class instance variables in the class constructor or pass the
variables as arguments in a method.
•
One drawback is cannot send any values back through a
constructor.
•
One of the reasons setting the instance variables to –1 and the get
methods to see the value of the variables.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
30
Passing Variables as Arguments of
a Method Continued
•
•
You can also use boolean variables to indicate bad data. The
boolean variable indicates if the input values passed business
rules validation.
For example:
if (myPayroll.blnInvalidRate) //did not pass validation if
{
//condition is true
txtRate.selectAll();
txtRate.selectAll();
showStatus(“Invalid Data”);
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
31
Checking for Numeric Values
•
The best way to check for non-numeric data is by catching
exceptions.
•
You can also use the isNaN method (is not a number) of the
Double and Float wrapper classes.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
32
Programming with Multiple Buttons
•
For any component that has an actionListener assigned triggers
the same actionPerformed method.
•
You need to determine which object triggered the
actionPerformed.
•
Java passes an ActionEvent object as an argument to the method,
in which you give the argument a name(evt) - actionPerformed
(ActionEvent evt).
•
The getSource method on the object will give the name of the
object that triggered the event.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
33
Programming with Multiple
Buttons Continued
•
•
•
For example: Object objSource = evt.getSource();
The next step is to use a condition to compare the object with the
names of your components.
For example :
if(objSource = = btnCalculate
|| objSource = = txtHours
|| objSource = = txtRate)
{
CalculatePay();
}
else
{
ClearTextFields();
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
34
Disabling and Enabling Buttons
•
You can disable a button by graying it out or you can hide a
button. It not advisable to hide a button as it frustrates the user.
•
You use the setEnabled method for the enabling and disabling
and setVisible method to show and hide.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
35
The setEnabled Method--General
Format
object.setEnabled(booleanValue);
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
36
The setEnabled Method--Examples
btnCalculate.setEnabled(true) ;
btnClear.setEnabled(false) ;
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
37
Precedence of Operators
Operator
++ -- * / %
+< > <= >=
= = !=
&&
||
?:
+* =+ =/ =/ =- =
Association
left to right*
left to right
left to right
left to right
left to right
left to right
right to left
right to left
* Increment and Decrement operators read right to left
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.