Download Programming with Java

Document related concepts

Functional programming wikipedia , lookup

Scala (programming language) wikipedia , lookup

C Sharp syntax wikipedia , lookup

Reactive programming wikipedia , lookup

Object-oriented programming wikipedia , lookup

Reserved word wikipedia , lookup

Falcon (programming language) wikipedia , lookup

Java (programming language) wikipedia , lookup

Java performance wikipedia , lookup

Structured programming wikipedia , lookup

For loop wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

Transcript
Programming with Java
1
Chapter 8
Using Lists, Choices and Looping
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
2
Objectives
•
Create and use a List object.
•
Update lists by using the add, remove, and removeAll
methods.
•
Determine which item in a list is selected.
•
Use the getItemCount method to determine the number of
items in a list.
•
Display a selected item from a list.
•
Use the Choice class to create a drop-down list.
•
Create program loops using do, while, and for statements.
•
Use the JList and JComboBox Swing components.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
3
Lists
•
The AWT List and Choice components allow you to set up a list of
items from which the user can make a selection.
•
Widths of the components vary upon the width of the items that you
add to the list.
•
The scroll bars appear automatically; and the scrolling is handled
automatically.
•
The items in a list are numbered internally with an index that starts
with zero.
•
When a user selects an item, you can retrieve the selected item or the
selected index.
•
You can assign an item listener and/or an action listener to a List and
respond whenever an item is selected.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
List and
Choice
Components
4
List components
JPanel with raised border
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
5
The List Component—
Constructors
List()
List(int rows)
List(int rows, boolean mode)
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
6
The List Component—Examples
List lstSelection = new List();
List lstDepartments = new List(5);
List lstSchools = new List(10, true);
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
7
Lists
•
If you use the empty constructor the default is 4 rows.
•
The mode specifies whether the user is allowed to select
multiple items from the list; set true for multiple selections;
default is false.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
8
Adding Items to a List
•
You can use the add method to add items to a list during
program design or program execution.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
9
The add Method—General Formats
add(String item);
add(String item, int position);
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
10
The add Method—Examples
lstDepartments.add("Accounting");
lstDepartments.add(strDepartment);
lstDepartments.add(strDepartment, 0);
lstDepartments.add(getText(txtNewDepartment));
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
11
Adding Items to a List
•
If you specify a number greater than the number of elements in
the list, the new item is added at the end of the list.
•
You can use the value of –1 to add to the end of the list.
•
Use the compareTo method to check if the text field has a blank
entry, so you don’t add a blank entry to the list.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
12
Applet screen for
Ch8ListUpdate
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
13
Clearing the List
•
You can also clear all the items from the list at runtime –
empty the list.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
14
The removeAll Method—General
Format
List.removeAll();
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
15
The removeAll Method—Example
lstDepartments.removeAll();
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
16
The getSelectedIndex Method
•
When a project is running and the user selects an item from the
list, you can retrieve the index number of the selected item.
•
The index number is retrieved by the getSelectedIndex method.
•
Recall that the first item of the list is 0. If the index = 6, then it
is the 7th item in the list.
•
If no item is selected in the list, the method returns a -1.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
17
The getItemCount Method
•
To find the number of items in the list, you can use the
getItemCount method.
•
The item count is always one higher than the highest index in
the list.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
18
Displaying One Element from a List
•
If you need to display a single item from a list, you can refer to
the text of an element using the getItem method or the
getSelectedItem method.
•
The getItem method requires an index.
•
The getSelectedItem retrieves the currently selected item.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
19
The getItem Method—General Format
getItem(int index)
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
20
The getSelectedItem Method—
General Format
getSelectedItem()
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
21
The getSelectedItem Method—
Examples
lblManager.setText(lstManagers.getSelectedItem());
String strDeptName;
strDeptName = lstDepartments.getSelectedItem();
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
22
Removing an Item from the List
•
You can remove individual items from the list.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
23
Deselecting all List Elements
•
Sometimes you need to reset a list so that no elements are
selected in the list.
•
You can do that with a combination of the deselect and
getSelectedIndex method.
•
For example,
lstDepartments.deselect(lstDepartment.getSelectedIndex());
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
24
The Choice Class
•
The Choice class provides a drop down list of items.
•
They are also referred to as pop-up menus.
•
You can use the choice class to a create menu rather than use a
series of buttons.
•
Use an item listener to respond when the user makes a selection.
•
You can use the Choice component’s index to determine which
option the user selects.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
25
The Choice Class Continued
•
The following code uses the switch statement and the
getSelectedIndex.
//Take action based on index of Choice menu
switch(chcActions.getSelectedIndex())
{
case 0:
addItem();
break;
case 1:
displayCount();
break;
case 2:
clearList();
break;
case 3:
removeItem();
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
26
Applet Screen for Ch8ListUpdate
using Choice Class
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
27
Applet Screen for Ch8ListUpdate
using Choice Class -Selections
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
28
Selected Members of the Choice and
List Classes
Method
Purpose
add(String value)
Add an element to the list.
addItem(String value)
Add an element to the list. (Method deprecated, so
should be avoided)
getItem(int position)
Return the element at the specified index position.
getItemCount()
Return the number of elements in the list.
getSelectedIndex()
Return the index of the selected item (starts with 0).
getSelectedItem()
Return the string value of the selected item.
insert(String value, int position)
Insert the string value at the specified position in
the list.
remove(int position)
Remove the element at the specified index position.
removeAll()
Clear the list.
select(int position)
Select (highlight) the element at the specified
position.
select(String value)
Select (highlight) the element that matches the
specified string.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
29
Using Choice for a Drop-Down List
•
The advantage is that the drop-down list uses less space and is
much cleaner on the interface.
•
The Choice class uses many of the same methods as the List
class.
•
The table on the previous slide shows some of the methods for
both the Choice class and List class.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
30
Loops
•
There is now way till now to repeat the same steps without
calling them a second time.
•
The process of repeating a series of instructions is called
looping.
•
An iteration is a single execution of statement(s) in the loop.
•
There are three types of loops, while loop, do while loop and the
for loop.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
31
The while and do Loops
•
Both the while loop and the do loop terminate based on a
condition you specify.
•
Both while and do loops the execution of the loop continues
while the condition is true.
•
For the while loop the condition is at the top of the loop.
•
For the do loop the condition is at the bottom of the loop.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
32
The while Loop—General Formats
while(condition)
statement;
while(condition)
{
statement(s);
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
33
The while Loop—Examples
while(intCount > 0)
statement;
while(intCount > 0)
{
statement(s);
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
34
The while and do Loops
•
You specify a condition, and only one statement is considered
the body of the loop unless you use braces.
•
Each time the execution reaches the while statement, the
condition is tested.
•
If the condition tests false the first time, the statements in the
loop are never executed.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
35
The while and do Loops Continued
•
•
For example : intTotal = 0;
while(intTotal = = 5)
{
//statements in a loop
}
Be careful, not to place the semicolon after the while statement.
This will terminate the loop.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
36
The do Loop—General Formats
do
statement;
while(condition);
do
{
statement(s);
}
while(condition);
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
37
The do Loop—Examples
do
statement;
while (intCount > 0);
do
{
statement(s);
}
while (intCount > 0);
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
38
Flowcharts of
the Logic for
a for while
Loops and do
Loops
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
39
The while and do Loops
•
The do loop tests for completion at the bottom of the loop,
which means the statements inside the loop will always
execute at least once.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
40
The boolean Data Type Revisited
• You will find boolean variables very useful when setting and
testing conditions for a loop.
• An example of using a boolean variable is when you want to
search through a list for a specific value.
• The item may or may not be found but if a match is found you
want to quit looking.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
41
The boolean Data Type Revisited
Continued
• Using a boolean variable is three step process.
First you must declare a variable and set its initial value(or
default setting of false).
When a particular situation occurs, set the variable to true.
A loop condition can check for true.
•Example:
boolean blnItemFound = false;
while (!blnItemFound)
//Continues as long as tests false
• A boolean variable is always in one of two states – true or false.
• Many programmers refer to boolean variables as switches or flags.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
42
The for Loop
•
When you want to repeat the statements in a loop a specific
number of times, use the for loop.
•
The for loop has a counter variable, called a loop index
which determines the number of times the statements inside
the loop will execute.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
43
The for Loop—General Form
for(initializationStatement; boolean Expression; updateCode)
statement;
for(initializationStatement; boolean Expression; updateCode)
{
statement(s);
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
44
The for Loop—Examples
for(intCount = 0; intCount <= 10; intCount++)
{
statement(s);
}
for(intCount = 0, fltTotal = 0.0f; intCount < 10; intCount++,
fltTotal += fltBalance)
{
statement(s);
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
45
Flowchart
Logic of a
for Loop
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
46
Using a for Loop Continued
• The same code is written twice with a subtle difference.
• There are no statements in the loop for the second example, as
all the calculation is carried out in the for statement.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
47
Using a for Loop
• Notice that it is legal to declare a new integer variable for the loop index
inside the for expression.
• public void actionPerformed(ActionEvent event)
{
//Add the numbers between the start and end
int intStart = Integer.valueOf(txtStart.getText()).intValue();
int intEnd = Integer.valueOf(txtEnd.getText()).intValue();
int intTotal = 0;
for(int intCount = intStart; intCount <= intEnd; intCount++)
intTotal += intCount;
lblMessage.setText("Total: " + intTotal);
}
Notice that the preceding for loop could also be written like this:
for(int intCount = intStart; intCount < intEnd; intCount++, intTotal +=
intCount);
lblMessage.setText("Total: " + intTotal);
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
48
Conditions Satisfied before a Loop
Entry
•
•
There are times when the final value is already reached before
the entry of the loop.
In that case, the body of the loop will never be executed.
//An unexecutable loop
int intFinal = 5;
for(intIndex = 6; intIndex < intFinal; intIndex++)
{
//The execution will never reach here
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
49
Endless Loops
•
•
•
•
Your code can get into a loop that is impossible to exit.
Changing the variable inside a loop is considered poor practice
and that may also lead to endless loops.
Example:
// Poor Programming
for(intIndex = 1; intIndex < 10; intIndex++)
{
intIndex = 1;
}
or
for(;;)
Notice that the statement above is acceptable in Java.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
50
Exiting Loops
•
You can exit out of the program execution manually or close the
Applet’s viewer or Browser window or you can use the
Windows system to close the program execution (Ctrl + Alt +
Del).
•
Usually loops should proceed to normal completion but on
occasions you have to terminate the loop before it reaches the
final value.
•
You can use a break statement to exit earlier from the loop.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
51
Swing Lists
•
•
The Swing components in JFC contain a list as well as a combo
box.
You will find Swing lists(JList and JComboBox) have
significant advantages over the AWT lists (List and Choice).
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
52
Setting List Values
• A nice addition to lists in Swing is that you can directly add items
to the list.
• This technique uses an array.
• Create string variable with square brackets and then you can
several string items to the same variable.
• We can then pass the string variable name to the argument of the
list.
• For example:
String strVegetables[] = {"Broccoli","Cauliflower",
"Eggplant","Lima Beans","Potatoes"};
JList lstVegetables = new JList(strVegetables);
• Another advantage of Swing lists over those in AWT is the ability
to have non-string elements.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
53
Editing the Text in a Combo Box
•
•
•
•
•
•
The JComboBox looks like a drop-down list.
You can also set the text portion of the list to allow the user to
enter a new value.
To make a combo box editable, call the setEditable method.
For example:
cboFruit.setEditable(true);
Note that making the combo box editable, does not automatically
add to the list.
You can do two things to add to the list, you can add a button or
assign an actionListener to the combo box, which will fire the
actionPerformed event when the user presses the Enter key.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
54
Scrolling Lists
•
•
•
•
In the AWT components List and Choice add scroll bars
automatically when the list of element exceeds number of rows
visible.
In Swing, JComboBox adds as scroll bar automatically but for
a JList it doesn’t.
You need to do little extra programming to add a scroll bar.
Look at the following example:
//Set up lstVegetables for scrolling
lstVegetables.setVisibleRowCount(4);
JScrollPane scrollList = new JScrollPane();
scrollList.setViewportView(lstVegetables);
pnlUI.add(scrollList); //Add lstVegetables in a viewport
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
55
Scrolling Lists Continued
•
You add the list to the scroll bar pane using the
setViewportView method.
•
Then you can add scroll pane (JScrollPane) to the Content
Pane rather than adding directly to the list component.
•
You set the number of rows visible using the
SetVisibleRowCount method to the list component.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.