Java Reference
In-Depth Information
Display 14.2
A for-each Loop Used with an
ArrayList
(part 2 of 2)
19 System.out.print("More items for the list? ");
20 answer = keyboard.nextLine();
21
if
(!(answer.equalsIgnoreCase("yes")))
22 done =
true
;
23 }
24 System.out.println("The list contains:");
25 for (String entry : toDoList)
26 System.out.println(entry);
27 }
28 }
Sample Dialogue
Enter list entries, when prompted.
Input an entry:
Practice Dancing.
More items for the list?
yes
Input an entry:
Buy tickets.
More items for the list?
yes
Input an entry:
Pack clothes.
More items for the list?
no
The list contains:
Practice Dancing.
Buy tickets.
Pack clothes.
Self-Test Exercises
8. Suppose
numberList
is an object of the class
ArrayList<Double>
. Give code
that will output all the elements in
numberList
to the screen.
9. Write a class for sorting strings into lexicographic order that follows the outline
of the class
SelectionSort
in Display 6.11 of Chapter 6 . Your definition,
however, will use an
ArrayList
of the class
ArrayList<String>
, rather than
an array of elements of type
double
. For words, lexicographic order reduces to
alphabetic order if all the words are in either all lowercase or all uppercase letters.
You can compare two strings to see which is lexicographically first by using
the
String
method
compareTo
. For strings
s1
and
s2
,
s1.compareTo(s2)
returns a negative number if
s1
is lexicographically before
s2
, returns
0
if
s1
equals
s2
, and returns a positive number if
s1
is lexicographically after
s2
. Call